Skip to content

Responses

The Basics

Responses

Introduction

Every route and handler in your application returns an HTTP response to send back to the user's browser or API client. In Laravel, every handler returns a *web.Response, and the web package has a function for each kind of response, such as web.JSON, web.View, and web.Redirect.

Whether a handler returns plain text, JSON, a rendered view, a redirect, a file download, or a live stream, Laravel takes care of the status code, headers, and body for you. Each function returns a response that you may keep changing before you return it, such as by setting its status code or attaching a header.

Creating responses

Text and JSON

The most basic response is plain text, which you return with web.Text:

1package routes
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/routing"
6 "go.laravel.com/web"
7)
8 
9func Web(route *routing.Router, cfg *config.Config) {
10 route.Get("/", func(r *web.Request) *web.Response {
11 return web.Text("Hello World")
12 })
13}
1package routes
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/routing"
6 "go.laravel.com/web"
7)
8 
9func Web(route *routing.Router, cfg *config.Config) {
10 route.Get("/", func(r *web.Request) *web.Response {
11 return web.Text("Hello World")
12 })
13}

When building an API or returning structured data, pass any value to web.JSON. Laravel encodes the value as JSON and sets the Content-Type header to application/json. Structs are encoded by their json tags:

1package health
2 
3import "go.laravel.com/web"
4 
5type Health struct {
6 Status string `json:"status"`
7 Version string `json:"version"`
8}
9 
10func Show(r *web.Request) *web.Response {
11 return web.JSON(Health{Status: "ok", Version: "1.0.0"})
12}
1package health
2 
3import "go.laravel.com/web"
4 
5type Health struct {
6 Status string `json:"status"`
7 Version string `json:"version"`
8}
9 
10func Show(r *web.Request) *web.Response {
11 return web.JSON(Health{Status: "ok", Version: "1.0.0"})
12}

For a small payload where defining a struct would add nothing, you may pass a map instead:

1return web.JSON(map[string]any{"status": "ok", "version": "1.0.0"})
1return web.JSON(map[string]any{"status": "ok", "version": "1.0.0"})

Since models are structs with json tags, you may also return a model or a slice of models:

1package users
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10func Index(r *web.Request) *web.Response {
11 users, err := model.Query[models.User]().Get(r)
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 return web.JSON(users)
17}
1package users
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10func Index(r *web.Request) *web.Response {
11 users, err := model.Query[models.User]().Get(r)
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 return web.JSON(users)
17}

Any field tagged json:"-" is left out of the JSON. Your application's User model tags its Password and RememberToken fields this way, so they aren't exposed in JSON responses.

HTML

When you want to render an HTML page on the server, return a view with web.View. Pass the view's name and the data it renders:

1package pages
2 
3import "go.laravel.com/web"
4 
5func About(r *web.Request) *web.Response {
6 return web.View("about", map[string]any{"Company": "Laravel"})
7}
1package pages
2 
3import "go.laravel.com/web"
4 
5func About(r *web.Request) *web.Response {
6 return web.View("about", map[string]any{"Company": "Laravel"})
7}

Sometimes you already have HTML that you trust, such as a terms of service page that your build step generates from Markdown. Pass it to web.HTML to send it as an HTML page. web.HTML sends the string exactly as you give it, without escaping it, so never put a value from your users in it. In this example, the generated terms.html sits beside the handler's file, and //go:embed builds it into your application:

1package legal
2 
3import (
4 _ "embed"
5 
6 "go.laravel.com/web"
7)
8 
9//go:embed terms.html
10var terms string
11 
12func Terms(r *web.Request) *web.Response {
13 return web.HTML(terms)
14}
1package legal
2 
3import (
4 _ "embed"
5 
6 "go.laravel.com/web"
7)
8 
9//go:embed terms.html
10var terms string
11 
12func Terms(r *web.Request) *web.Response {
13 return web.HTML(terms)
14}

Inertia

If you'd like to build your frontend in React, Vue, or Svelte without building and maintaining a separate API, you may return an Inertia response instead of a server-rendered view. Pass the name of your frontend page component and its props to inertia.Render:

1package posts
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return inertia.Render("Posts/Show", inertia.Props{"post": post})
18}
1package posts
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return inertia.Render("Posts/Show", inertia.Props{"post": post})
18}

To learn more about rendering Inertia pages, sharing data, and handling forms on the frontend, check out the Inertia guide.

Created and no content

When building a JSON API, you'll usually respond with 201 Created after creating a resource and 204 No Content after deleting one. Laravel provides web.Created to encode a value as JSON with a 201 status, and web.NoContent to send an empty 204 response.

In this posts handler package, StorePost is the post's validated input, Store creates the post for the logged-in user, and Destroy deletes the post that the route names:

1package posts
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/validation"
6 "go.laravel.com/validation/rule"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type StorePost struct {
13 Title string `json:"title"`
14 Body string `json:"body"`
15}
16 
17func (f *StorePost) Rules() validation.Rules {
18 return validation.For(f,
19 rule.Field(&f.Title, rule.Required, rule.Max(255)),
20 rule.Field(&f.Body, rule.Required),
21 )
22}
23 
24func Store(r *web.Request) *web.Response {
25 form, err := r.Validate[StorePost]()
26 if err != nil {
27 return web.Fail(err)
28 }
29 
30 post := models.Post{UserID: models.CurrentUser(r).ID, Title: form.Title, Body: &form.Body}
31 if err := model.Create(r, &post); err != nil {
32 return web.Fail(err)
33 }
34 
35 return web.Created(post)
36}
37 
38func Destroy(r *web.Request) *web.Response {
39 post, err := model.FromRoute[models.Post](r, "post")
40 if err != nil {
41 return web.Fail(err)
42 }
43 
44 if err := model.Delete(r, &post); err != nil {
45 return web.Fail(err)
46 }
47 
48 return web.NoContent()
49}
1package posts
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/validation"
6 "go.laravel.com/validation/rule"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type StorePost struct {
13 Title string `json:"title"`
14 Body string `json:"body"`
15}
16 
17func (f *StorePost) Rules() validation.Rules {
18 return validation.For(f,
19 rule.Field(&f.Title, rule.Required, rule.Max(255)),
20 rule.Field(&f.Body, rule.Required),
21 )
22}
23 
24func Store(r *web.Request) *web.Response {
25 form, err := r.Validate[StorePost]()
26 if err != nil {
27 return web.Fail(err)
28 }
29 
30 post := models.Post{UserID: models.CurrentUser(r).ID, Title: form.Title, Body: &form.Body}
31 if err := model.Create(r, &post); err != nil {
32 return web.Fail(err)
33 }
34 
35 return web.Created(post)
36}
37 
38func Destroy(r *web.Request) *web.Response {
39 post, err := model.FromRoute[models.Post](r, "post")
40 if err != nil {
41 return web.Fail(err)
42 }
43 
44 if err := model.Delete(r, &post); err != nil {
45 return web.Fail(err)
46 }
47 
48 return web.NoContent()
49}

If you'd also like to tell the client where the new post lives, attach a Location header with the post's URL. urls.Route builds the URL from the route's name and the post:

1link, err := urls.Route(r, "posts.show", "post", &post)
2if err != nil {
3 return web.Fail(err)
4}
5 
6return web.Created(post).WithHeader("Location", link)
1link, err := urls.Route(r, "posts.show", "post", &post)
2if err != nil {
3 return web.Fail(err)
4}
5 
6return web.Created(post).WithHeader("Location", link)

Status codes and headers

Sometimes a handler needs to respond with a status code other than 200 OK, such as 202 Accepted after queuing a background export. To set the status code, chain WithStatus onto any response:

1package exports
2 
3import (
4 "net/http"
5 
6 "go.laravel.com/web"
7)
8 
9func Store(r *web.Request) *web.Response {
10 // Queue the export...
11 
12 return web.Text("Your export is being prepared.").WithStatus(http.StatusAccepted)
13}
1package exports
2 
3import (
4 "net/http"
5 
6 "go.laravel.com/web"
7)
8 
9func Store(r *web.Request) *web.Response {
10 // Queue the export...
11 
12 return web.Text("Your export is being prepared.").WithStatus(http.StatusAccepted)
13}

To attach a header to any response, chain WithHeader, once for each header. A header you attach replaces any existing header of the same name, including defaults such as a view's Content-Type:

1func Feed(r *web.Request) *web.Response {
2 return web.View("feed", nil).WithHeader("Content-Type", "application/rss+xml")
3}
4 
5func Report(r *web.Request) *web.Response {
6 return web.View("reports.show", nil).
7 WithHeader("Cache-Control", "no-store").
8 WithHeader("X-Frame-Options", "DENY")
9}
1func Feed(r *web.Request) *web.Response {
2 return web.View("feed", nil).WithHeader("Content-Type", "application/rss+xml")
3}
4 
5func Report(r *web.Request) *web.Response {
6 return web.View("reports.show", nil).
7 WithHeader("Cache-Control", "no-store").
8 WithHeader("X-Frame-Options", "DENY")
9}

If you'd like to add a second value to a header instead of replacing it, use the response's Header field, which is a standard http.Header, as in res.Header.Add("Link", next). To set caching headers on a whole route, use the CacheHeaders middleware.

Since every kind of response is a *web.Response, different branches of a handler may return different kinds of responses. For example, this handler answers an API client with JSON and a browser with a view:

1func Show(r *web.Request) *web.Response {
2 report := map[string]any{"title": "Q3 Sales", "total": 1200}
3 
4 if r.ExpectsJSON() {
5 return web.JSON(report)
6 }
7 
8 return web.View("reports.show", report)
9}
1func Show(r *web.Request) *web.Response {
2 report := map[string]any{"title": "Q3 Sales", "total": 1200}
3 
4 if r.ExpectsJSON() {
5 return web.JSON(report)
6 }
7 
8 return web.View("reports.show", report)
9}

To respond with an error status, return web.Abort with the status, or web.Fail with an error. Laravel renders the error as a page for browsers and as JSON for API clients, and sends any headers and cookies you chain onto the error response along with it:

1return web.Abort(http.StatusServiceUnavailable).WithHeader("Retry-After", "60")
1return web.Abort(http.StatusServiceUnavailable).WithHeader("Retry-After", "60")

Cookies

Sometimes a handler needs to store a small value in the user's browser, such as their preferred color theme. You may attach a cookie to any outgoing response with WithCookie, and remove a cookie from the browser with WithoutCookie. The cookie package builds the cookie, and cookie.Forever makes one that the browser keeps for as long as browsers allow:

1package settings
2 
3import (
4 "go.laravel.com/cookie"
5 "go.laravel.com/web"
6)
7 
8func UpdateTheme(r *web.Request) *web.Response {
9 return web.Back().WithCookie(cookie.Forever("theme", "dark"))
10}
11 
12func ForgetTheme(r *web.Request) *web.Response {
13 return web.Back().WithoutCookie("theme")
14}
1package settings
2 
3import (
4 "go.laravel.com/cookie"
5 "go.laravel.com/web"
6)
7 
8func UpdateTheme(r *web.Request) *web.Response {
9 return web.Back().WithCookie(cookie.Forever("theme", "dark"))
10}
11 
12func ForgetTheme(r *web.Request) *web.Response {
13 return web.Back().WithoutCookie("theme")
14}

To learn more about cookie lifetimes, attributes, and how Laravel encrypts cookies, check out the cookies guide.

Redirects

After saving a form or completing an action, you'll usually send the user to another page rather than render one directly. To redirect to a path or a full URL, such as a payment provider's checkout page, return web.Redirect. To send the user back to the page they came from, return web.Back:

1func Dashboard(r *web.Request) *web.Response {
2 return web.Redirect("/home/dashboard")
3}
4 
5func Update(r *web.Request) *web.Response {
6 // Save the user's settings...
7 
8 return web.Back()
9}
1func Dashboard(r *web.Request) *web.Response {
2 return web.Redirect("/home/dashboard")
3}
4 
5func Update(r *web.Request) *web.Response {
6 // Save the user's settings...
7 
8 return web.Back()
9}

You don't need to redirect back yourself when a submitted form is invalid. When you pass a validation error to web.Fail, Laravel redirects the user back to the form with the errors and their input. To learn more, check out the validation guide's section on validation responses.

Redirecting to routes

To redirect to one of your application's named routes, return web.RedirectRoute with the route's name. If you change the route's path later, the redirect follows it. Pass the route's parameters after the name, as names and values in pairs. For example, a handler that creates a post may redirect to the new post's page:

1return web.RedirectRoute("posts.show", "post", &post)
1return web.RedirectRoute("posts.show", "post", &post)

Laravel fills the post parameter with the post's ID, or with its slug when the route names the slug, as in /posts/{post:slug}. To learn more, check out the URL generation guide's section on models and your own types.

To attach query parameters to a redirect, such as the active tab or a filter, chain WithQuery with a url.Values. To scroll the user to a specific section of the destination page, such as the comments section of a post, chain WithFragment. For example, this redirects to /posts/42?tab=comments#reply:

1return web.RedirectRoute("posts.show", "post", &post).
2 WithQuery(url.Values{"tab": {"comments"}}).
3 WithFragment("reply")
1return web.RedirectRoute("posts.show", "post", &post).
2 WithQuery(url.Values{"tab": {"comments"}}).
3 WithFragment("reply")

Redirecting with flashed session data

Redirecting to a new page and flashing data to the session often go together, such as showing a banner that confirms a form was saved. To flash a value for the next request, chain With onto the redirect:

1func Update(r *web.Request) *web.Response {
2 // Update the user's profile...
3 
4 return web.Back().With("status", "Profile saved.")
5}
1func Update(r *web.Request) *web.Response {
2 // Update the user's profile...
3 
4 return web.Back().With("status", "Profile saved.")
5}

The flashed value is available only for the next request. A view may read it with session "status". If your application uses Inertia, flash the value with inertia.Flash instead, so the next page receives it in its flash data.

If a check in your handler fails, such as an expired coupon, you may send the user back with an error next to that field. Chain WithError onto the redirect with the field name and message, and chain WithInput so the form can fill itself back in:

1return web.Back().WithError("coupon", "That coupon has expired.").WithInput()
1return web.Back().WithError("coupon", "That coupon has expired.").WithInput()

Chain additional WithError calls to attach errors to more fields, or pass a *web.InputError to WithErrors when redirecting after a failed form validation. Because flash data is stored in the session, With, WithInput, WithError, and WithErrors on redirects only work on routes in the web middleware group.

Redirecting to the intended page

When a guest visits a page that requires authentication, the Authenticate middleware stores the page's URL in the session and sends the guest to your login page. After they log in, auth.RedirectIntended sends them on to the page they originally requested. If the session holds no such page, it redirects to the path you pass it (or use auth.RedirectIntendedRoute to fall back to a named route):

1package login
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/web"
6)
7 
8func Store(r *web.Request) *web.Response {
9 // Log the user in...
10 
11 return auth.RedirectIntendedRoute("dashboard")
12}
1package login
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/web"
6)
7 
8func Store(r *web.Request) *web.Response {
9 // Log the user in...
10 
11 return auth.RedirectIntendedRoute("dashboard")
12}

Redirect status codes

By default, redirects respond with a 302 Found status code. If you need a different status code, chain WithStatus onto the redirect, such as http.StatusSeeOther for a 303, or http.StatusMovedPermanently for a page that has moved for good:

1return web.Redirect("/login").WithStatus(http.StatusSeeOther)
2 
3return web.Redirect("/pricing").WithStatus(http.StatusMovedPermanently)
1return web.Redirect("/login").WithStatus(http.StatusSeeOther)
2 
3return web.Redirect("/pricing").WithStatus(http.StatusMovedPermanently)

If the old address needs no handler of its own, you may register a redirect route instead.

If your application uses Inertia, Laravel automatically turns 302 redirects into 303 after PUT, PATCH, and DELETE requests, so you don't need to set the status yourself.

Files

Some files shouldn't be publicly accessible, such as invoices and reports that only their owner should see. After checking that the user has access, you may return a file on disk from your handler.

File downloads

To prompt the user's browser to download a file, return web.Download with the file's path and the name the browser should save it under. Pass "" as the name to keep the file's own name:

1func Report(r *web.Request) *web.Response {
2 return web.Download("storage/reports/q3.pdf", "Q3 Report.pdf")
3}
1func Report(r *web.Request) *web.Response {
2 return web.Download("storage/reports/q3.pdf", "Q3 Report.pdf")
3}

File responses

To display a file directly in the browser instead of downloading it, such as an image or a PDF, return web.File. For example, this handler shows the invoice whose ID the route names, as in /invoices/{invoice}:

1package invoices
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 id, err := r.PathInt("invoice")
11 if err != nil {
12 return web.Fail(err)
13 }
14 
15 return web.File(fmt.Sprintf("storage/invoices/%d.pdf", id))
16}
1package invoices
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 id, err := r.PathInt("invoice")
11 if err != nil {
12 return web.Fail(err)
13 }
14 
15 return web.File(fmt.Sprintf("storage/invoices/%d.pdf", id))
16}

For both web.Download and web.File, Laravel sets the Content-Type header from the file's extension and answers conditional and range requests, so browsers can cache the file and resume interrupted downloads. If the file doesn't exist, Laravel responds with a 404. Relative paths resolve against your application's base path rather than the process's working directory.

Never build a file's path directly from untrusted user input, such as a raw filename from r.PathValue. A path containing .. or a leading / could allow a user to read any file your application can read. Use an integer ID, as r.PathInt returns, look up the path in your database, or serve the file from a storage disk instead.

If a file is stored without an extension, set its content type yourself with WithHeader:

1return web.File(fmt.Sprintf("storage/avatars/%d", id)).WithHeader("Content-Type", "image/png")
1return web.File(fmt.Sprintf("storage/avatars/%d", id)).WithHeader("Content-Type", "image/png")

If you generated a temporary file on disk only for this response, such as a one-off export, register a function with r.OnFinish that removes the file. Laravel calls the function once the response has been sent:

1path := "storage/exports/tmp-users.csv"
2 
3// Write the export...
4 
5r.OnFinish(func() { os.Remove(path) })
6 
7return web.Download(path, "users.csv")
1path := "storage/exports/tmp-users.csv"
2 
3// Write the export...
4 
5r.OnFinish(func() { os.Remove(path) })
6 
7return web.Download(path, "users.csv")

For a file on one of your storage disks, such as an S3 bucket, use web.DiskFile and web.DiskDownload. Both take the disk and the file's path on the disk, and storage.From returns your application's default disk:

1return web.DiskDownload(storage.From(r), "invoices/2026-11.pdf", "invoice.pdf")
1return web.DiskDownload(storage.From(r), "invoices/2026-11.pdf", "invoice.pdf")

Laravel serves the files in your public directory without a route. Use web.File and web.Download for private files that your handlers decide whether to serve.

Downloads of generated content

Sometimes you want to offer generated content as a download, such as a CSV export, without writing a temporary file to disk first. Return web.Attachment with the file's name and any io.Reader, and Laravel sets the content type from the name:

1package users
2 
3import (
4 "encoding/csv"
5 "strings"
6 
7 "go.laravel.com/model"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13func Export(r *web.Request) *web.Response {
14 users, err := model.Query[models.User]().Get(r)
15 if err != nil {
16 return web.Fail(err)
17 }
18 
19 var export strings.Builder
20 
21 rows := csv.NewWriter(&export)
22 rows.Write([]string{"name", "email"})
23 for _, user := range users {
24 rows.Write([]string{user.Name, user.Email})
25 }
26 rows.Flush()
27 
28 return web.Attachment("users.csv", strings.NewReader(export.String()))
29}
1package users
2 
3import (
4 "encoding/csv"
5 "strings"
6 
7 "go.laravel.com/model"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13func Export(r *web.Request) *web.Response {
14 users, err := model.Query[models.User]().Get(r)
15 if err != nil {
16 return web.Fail(err)
17 }
18 
19 var export strings.Builder
20 
21 rows := csv.NewWriter(&export)
22 rows.Write([]string{"name", "email"})
23 for _, user := range users {
24 rows.Write([]string{user.Name, user.Email})
25 }
26 rows.Flush()
27 
28 return web.Attachment("users.csv", strings.NewReader(export.String()))
29}

web.Attachment sends the content as it reads it, so you may also pass on a download from another service without holding it in memory. For example, this handler sends an invoice PDF that a billing service returns. Laravel closes the billing service's response body once the download has been sent:

1package invoices
2 
3import (
4 "net/http"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/web"
8)
9 
10func Download(r *web.Request) *web.Response {
11 invoice, err := httpclient.EnsureSuccessful().
12 Stream(r, http.MethodGet, "https://billing.example.com/invoices/7.pdf")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return web.Attachment("invoice.pdf", invoice.Body)
18}
1package invoices
2 
3import (
4 "net/http"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/web"
8)
9 
10func Download(r *web.Request) *web.Response {
11 invoice, err := httpclient.EnsureSuccessful().
12 Stream(r, http.MethodGet, "https://billing.example.com/invoices/7.pdf")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return web.Attachment("invoice.pdf", invoice.Body)
18}

For a large export, holding the entire file in memory isn't practical. Instead, return a web.StreamDownload, which sends each row as your code writes it.

Streamed responses

Some responses take a while to produce, such as an AI model's reply that arrives token by token or the live output of a deployment. Instead of waiting until the entire response is ready, a streamed response sends each piece to the client as soon as your code writes it.

To stream a response, return web.Stream with a function that writes the body. Laravel calls the function once your handler returns, and sends each write to the client right away:

1package deploys
2 
3import (
4 "fmt"
5 "io"
6 
7 "go.laravel.com/web"
8)
9 
10func Deploy(r *web.Request) *web.Response {
11 return web.Stream(func(w io.Writer) error {
12 for _, step := range []string{"Building", "Migrating", "Done"} {
13 // Run the step...
14 
15 if _, err := fmt.Fprintln(w, step); err != nil {
16 return err
17 }
18 }
19 
20 return nil
21 })
22}
1package deploys
2 
3import (
4 "fmt"
5 "io"
6 
7 "go.laravel.com/web"
8)
9 
10func Deploy(r *web.Request) *web.Response {
11 return web.Stream(func(w io.Writer) error {
12 for _, step := range []string{"Building", "Migrating", "Done"} {
13 // Run the step...
14 
15 if _, err := fmt.Fprintln(w, step); err != nil {
16 return err
17 }
18 }
19 
20 return nil
21 })
22}

A write fails once the client disconnects, so returning the write's error stops your function. If your function returns any other error, Laravel reports the error and ends the response abruptly, so the client can tell the stream was cut short. By the time your function runs, Laravel has already sent the status and headers, so an error can't become an error page. Check what you can, such as whether the user may see the deployment, in the handler before you return the stream.

Streamed responses use text/plain by default. To send another content type, chain WithHeader onto the response:

1func Answer(r *web.Request) *web.Response {
2 return web.Stream(func(w io.Writer) error {
3 _, err := io.WriteString(w, "# Summary\n\nHere is the streamed Markdown reply.")
4 
5 return err
6 }).WithHeader("Content-Type", "text/markdown")
7}
1func Answer(r *web.Request) *web.Response {
2 return web.Stream(func(w io.Writer) error {
3 _, err := io.WriteString(w, "# Summary\n\nHere is the streamed Markdown reply.")
4 
5 return err
6 }).WithHeader("Content-Type", "text/markdown")
7}

If you'd like the browser to save the stream as a file, return web.StreamDownload instead. It takes the file's name and the same kind of function, and sets the content type from the name. For example, this handler streams every post as a CSV row, reading the posts from the database 1,000 at a time with LazyByID:

1package posts
2 
3import (
4 "encoding/csv"
5 "io"
6 "strconv"
7 
8 "go.laravel.com/model"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14func Export(r *web.Request) *web.Response {
15 posts := model.Query[models.Post]().LazyByID(r, 1000)
16 
17 return web.StreamDownload("posts.csv", func(w io.Writer) error {
18 rows := csv.NewWriter(w)
19 for post, err := range posts {
20 if err != nil {
21 return err
22 }
23 if err := rows.Write([]string{strconv.FormatInt(post.ID, 10), post.Title}); err != nil {
24 return err
25 }
26 }
27 
28 rows.Flush()
29 
30 return rows.Error()
31 })
32}
1package posts
2 
3import (
4 "encoding/csv"
5 "io"
6 "strconv"
7 
8 "go.laravel.com/model"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14func Export(r *web.Request) *web.Response {
15 posts := model.Query[models.Post]().LazyByID(r, 1000)
16 
17 return web.StreamDownload("posts.csv", func(w io.Writer) error {
18 rows := csv.NewWriter(w)
19 for post, err := range posts {
20 if err != nil {
21 return err
22 }
23 if err := rows.Write([]string{strconv.FormatInt(post.ID, 10), post.Title}); err != nil {
24 return err
25 }
26 }
27 
28 rows.Flush()
29 
30 return rows.Error()
31 })
32}

The route's timeout covers the handler but not the stream, so a stream may run for as long as it has something to send.

Laravel saves the session after your handler returns and before it sends the response body. Make any session changes in the handler before returning the stream, not inside the function that writes it.

On the frontend, you may consume a streamed response with the useStream hook from @laravel/stream-react or @laravel/stream-vue. Install the package for your frontend:

1npm install @laravel/stream-react
1npm install @laravel/stream-react

useStream sends a POST request, so register the route with route.Post in routes/web.go, such as route.Post("/deploy", deploys.Deploy). The hook reads the CSRF token from the XSRF-TOKEN cookie that the web group sets. Once you invoke send, the hook automatically appends each incoming chunk to data:

1import { useStream } from "@laravel/stream-react";
2 
3export default function Deploy() {
4 const { data, isFetching, isStreaming, send } = useStream("/deploy");
5 
6 return (
7 <div>
8 <pre>{data}</pre>
9 {isFetching && <p>Connecting...</p>}
10 <button onClick={() => send({})} disabled={isStreaming}>
11 Deploy
12 </button>
13 </div>
14 );
15}
1import { useStream } from "@laravel/stream-react";
2 
3export default function Deploy() {
4 const { data, isFetching, isStreaming, send } = useStream("/deploy");
5 
6 return (
7 <div>
8 <pre>{data}</pre>
9 {isFetching && <p>Connecting...</p>}
10 <button onClick={() => send({})} disabled={isStreaming}>
11 Deploy
12 </button>
13 </div>
14 );
15}

Streamed JSON responses

When you need to return a large list as JSON, such as every user in your database, loading the entire list into memory at once can be slow and expensive. Instead, return web.StreamJSON, which encodes and sends each item as it arrives.

Pass web.StreamJSON an iterator, such as a model query's LazyByID, which reads the rows from the database in batches. Laravel sends the items as a JSON array:

1package users
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10func Index(r *web.Request) *web.Response {
11 return web.StreamJSON(model.Query[models.User]().LazyByID(r, 500)) // [{"id":1,...},...]
12}
1package users
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10func Index(r *web.Request) *web.Response {
11 return web.StreamJSON(model.Query[models.User]().LazyByID(r, 500)) // [{"id":1,...},...]
12}

If you'd rather wrap the array in a JSON object under a top-level key, build a web.JSONStream with a Key and call its Response method:

1return web.JSONStream[models.User]{
2 Items: model.Query[models.User]().LazyByID(r, 500),
3 Key: "users",
4}.Response() // {"users":[{"id":1,...},...]}
1return web.JSONStream[models.User]{
2 Items: model.Query[models.User]().LazyByID(r, 500),
3 Key: "users",
4}.Response() // {"users":[{"id":1,...},...]}

If the query fails part way, Laravel reports the error and ends the response abruptly, so the client sees incomplete JSON rather than a list that looks finished.

On the frontend, the useJsonStream hook from @laravel/stream-react or @laravel/stream-vue reads the streamed response and parses the JSON once the stream finishes:

1import { useJsonStream } from "@laravel/stream-react";
2 
3type User = {
4 id: number;
5 name: string;
6 email: string;
7};
8 
9export default function Users() {
10 const { data, send } = useJsonStream<{ users: User[] }>("/users");
11 
12 return (
13 <div>
14 <ul>
15 {data?.users.map((user) => (
16 <li key={user.id}>{user.name}</li>
17 ))}
18 </ul>
19 <button onClick={() => send({})}>Load Users</button>
20 </div>
21 );
22}
1import { useJsonStream } from "@laravel/stream-react";
2 
3type User = {
4 id: number;
5 name: string;
6 email: string;
7};
8 
9export default function Users() {
10 const { data, send } = useJsonStream<{ users: User[] }>("/users");
11 
12 return (
13 <div>
14 <ul>
15 {data?.users.map((user) => (
16 <li key={user.id}>{user.name}</li>
17 ))}
18 </ul>
19 <button onClick={() => send({})}>Load Users</button>
20 </div>
21 );
22}

Event streams

When you want to push updates to a page as things happen on the server, such as a dashboard that shows how many posts there are as writers publish them, send server-sent events (text/event-stream) over one long-lived connection. Return web.StreamEvents with a function that calls send for each web.Event and returns any error. An event without a Name is sent as an update event. For example, this handler sends the number of posts every five seconds:

1package posts
2 
3import (
4 "time"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12func Count(r *web.Request) *web.Response {
13 return web.StreamEvents(func(send func(web.Event) error) error {
14 ticker := time.NewTicker(5 * time.Second)
15 defer ticker.Stop()
16 
17 for {
18 count, err := model.Query[models.Post]().Count(r)
19 if err != nil {
20 return err
21 }
22 if err := send(web.Event{Data: count}); err != nil {
23 return err
24 }
25 
26 select {
27 case <-r.Done():
28 return nil
29 case <-ticker.C:
30 }
31 }
32 })
33}
1package posts
2 
3import (
4 "time"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12func Count(r *web.Request) *web.Response {
13 return web.StreamEvents(func(send func(web.Event) error) error {
14 ticker := time.NewTicker(5 * time.Second)
15 defer ticker.Stop()
16 
17 for {
18 count, err := model.Query[models.Post]().Count(r)
19 if err != nil {
20 return err
21 }
22 if err := send(web.Event{Data: count}); err != nil {
23 return err
24 }
25 
26 select {
27 case <-r.Done():
28 return nil
29 case <-ticker.C:
30 }
31 }
32 })
33}

send fails once the client disconnects, so returning its error stops the function cleanly. If your function returns any other error, Laravel reports it and ends the stream without sending the final </stream> event. Make the function stop when the request ends, as the example does with r.Done(), or it keeps running after the user leaves the page. If you already have an iter.Seq[web.Event] that can't fail, pass it to web.Events instead.

Laravel sends an event's Data as it is when the data is a string or a []byte, and as JSON otherwise. If you'd like to give an event a custom name that the browser can listen for separately, set its Name. To send HTML, such as a table row for each post as it's published, pass a web.Partial with a view's name and its data, and Laravel renders the view for the event:

1if err := send(web.Event{
2 Name: "post-published",
3 Data: web.Partial{View: "posts.row", Data: post},
4}); err != nil {
5 return err
6}
1if err := send(web.Event{
2 Name: "post-published",
3 Data: web.Partial{View: "posts.row", Data: post},
4}); err != nil {
5 return err
6}

On the frontend, the useEventStream hook from @laravel/stream-react or @laravel/stream-vue listens for update events and updates message as each one arrives:

1import { useEventStream } from "@laravel/stream-react";
2 
3export default function PostCount() {
4 const { message } = useEventStream("/posts/count");
5 
6 return <div>{message}</div>;
7}
1import { useEventStream } from "@laravel/stream-react";
2 
3export default function PostCount() {
4 const { message } = useEventStream("/posts/count");
5 
6 return <div>{message}</div>;
7}

When the iterator runs out of events, Laravel sends a final update event containing </stream> so the @laravel/stream hooks know the stream has finished. If you consume the stream manually with the browser's EventSource API, close the connection when </stream> arrives so the browser doesn't reconnect automatically:

1const source = new EventSource("/posts/count");
2 
3source.addEventListener("update", (event) => {
4 if (event.data === "</stream>") {
5 source.close();
6 
7 return;
8 }
9 
10 console.log(event.data);
11});
1const source = new EventSource("/posts/count");
2 
3source.addEventListener("update", (event) => {
4 if (event.data === "</stream>") {
5 source.close();
6 
7 return;
8 }
9 
10 console.log(event.data);
11});

If you'd like to send a different final event, or omit it altogether, build a web.EventStream and call its Response method:

1return web.EventStream{
2 Events: events,
3 End: &web.Event{Name: "done", Data: "complete"},
4}.Response()
5 
6return web.EventStream{
7 Events: events,
8 WithoutEndEvent: true,
9}.Response()
1return web.EventStream{
2 Events: events,
3 End: &web.Event{Name: "done", Data: "complete"},
4}.Response()
5 
6return web.EventStream{
7 Events: events,
8 WithoutEndEvent: true,
9}.Response()

While no events arrive, Laravel sends a comment every 15 seconds so proxies don't close the connection.

Responses of your own

If several handlers in your application return the same kind of response, you may give it a function of its own that returns a *web.Response. For example, an API that queues background work might define an Accepted function that encodes a payload as JSON with a 202 Accepted status:

1package responses
2 
3import (
4 "net/http"
5 
6 "go.laravel.com/web"
7)
8 
9// Accepted answers a request whose work was queued.
10func Accepted(value any) *web.Response {
11 return web.JSON(value).WithStatus(http.StatusAccepted)
12}
1package responses
2 
3import (
4 "net/http"
5 
6 "go.laravel.com/web"
7)
8 
9// Accepted answers a request whose work was queued.
10func Accepted(value any) *web.Response {
11 return web.JSON(value).WithStatus(http.StatusAccepted)
12}

Handlers may now return responses.Accepted(job), and because it returns a *web.Response, they may chain WithHeader, WithCookie, and WithoutCookie onto it as they would onto any other response.

Testing

To test the responses your routes return, send requests with the test client and chain assertions onto each response. For example, these tests check that /feed returns an RSS content type and that saving the profile redirects back with a status message. From sets the page the request comes from, and AssertRedirectBack checks that the response redirected to that page:

1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "app/tests"
8)
9 
10func TestTheFeedIsRSS(t *testing.T) {
11 tests.New(t).Get("/feed").
12 AssertOK().
13 AssertHeader("Content-Type", "application/rss+xml")
14}
15 
16func TestSavingTheProfileRedirectsBack(t *testing.T) {
17 tests.New(t).From("/profile").Post("/profile", url.Values{"name": {"Taylor"}}).
18 AssertRedirectBack().
19 AssertSessionHas("status", "Profile saved.")
20}
1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "app/tests"
8)
9 
10func TestTheFeedIsRSS(t *testing.T) {
11 tests.New(t).Get("/feed").
12 AssertOK().
13 AssertHeader("Content-Type", "application/rss+xml")
14}
15 
16func TestSavingTheProfileRedirectsBack(t *testing.T) {
17 tests.New(t).From("/profile").Post("/profile", url.Values{"name": {"Taylor"}}).
18 AssertRedirectBack().
19 AssertSessionHas("status", "Profile saved.")
20}

The test client reads a streamed response to its end before it returns, so AssertSee checks the stream's whole body. To learn more about asserting status codes, headers, cookies, redirects, and JSON responses, check out the testing guide's section on available assertions. If you'd like to inspect the page a redirect leads to, check out following redirects.