---
title: route.go
description: API reference for building experimental Go API endpoints with the route.go file convention.
url: "https://nextjs.org/docs/app/api-reference/file-conventions/route-go"
docs_index: /docs/llms.txt
lastUpdated: 2026-12-01
badge: "Experimental"
prerequisites:
  - "API Reference: /docs/app/api-reference"
  - "File-system conventions: /docs/app/api-reference/file-conventions"
---

> For an index of all documentation, see [/docs/llms.txt](/docs/llms.txt).

> This feature is currently experimental and subject to change, it’s not recommended for production. Try it out and share your feedback on [GitHub](https://github.com/vercel/next.js/issues).

`route.go` defines a Go Route Handler (API endpoint) in the App Router using Go's `net/http` request and response APIs.

```go highlight={10} title="app/api/hello/route.go"
package route

import (
  "encoding/json"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(map[string]string{"message": "Hello from Go!"})
}
```

> **Good to know:**
>
> - Go Route Handlers require `experimental.goRoutes` and Turbopack. Webpack is unsupported.
> - Go Route Handlers always execute dynamically. JavaScript route segment configuration, ISR, and `generateStaticParams` do not apply.
> - Go handlers run as compiled executables. JavaScript and TypeScript handlers, React rendering, and Pages Router pages continue to use Node.js.

## Setup

Enable the experiment in your Next.js configuration:

**TypeScript**

```ts title="next.config.ts" 
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: { goRoutes: true },
}

export default nextConfig
```

**JavaScript**

```js title="next.config.js" 
module.exports = {
  experimental: { goRoutes: true },
}
```

Install Go 1.24 or newer on `PATH`, or set `TURBOPACK_GO` to its executable path. Go is required for `next dev` and `next build`. `next start` runs the compiled executables without the Go compiler. Applications without Go handlers do not require Go.

To import SDK packages such as `next/go/proxy`, your project needs a Go module. Create one with `go mod init example.com/app` if needed, using `go 1.21` or newer in `go.mod`. `next dev` and `next build` add the `next/go` requirement and a local replacement pointing to the SDK in your installed `next` package. Commit the updated `go.mod`.

Both commands refresh the replacement when the installed SDK moves, including after pnpm upgrades, and log any changes. This can update a committed `go.mod` during CI builds.

## Reference

### HTTP Methods

Define top-level functions named `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, or `OPTIONS` in `route.go`. Each function handles the corresponding HTTP method, following the same method conventions as [`route.ts`](/docs/app/api-reference/file-conventions/route#http-methods).

Each function must accept `http.ResponseWriter` and `*http.Request`, in that order, and return no value. The Go compiler validates the signatures when compiling the route.

| Method                                    | Behavior                                                                                                                                                |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A method with a matching function         | Invoke that function.                                                                                                                                   |
| `HEAD` without a `HEAD` function          | Invoke `GET` if defined, with `r.Method == "HEAD"`. The HTTP server suppresses response body bytes. Otherwise, return `405`.                            |
| `OPTIONS` without an `OPTIONS` function   | Return `204` with an alphabetically sorted `Allow` header listing supported methods, including `OPTIONS` and the `HEAD` fallback when `GET` is defined. |
| Other methods without a matching function | Return `405`.                                                                                                                                           |

For example, a route defining `GET` and `POST` automatically responds to `OPTIONS` with `Allow: GET, HEAD, OPTIONS, POST`. Define `HEAD` or `OPTIONS` to override their automatic implementations.

### Parameters

#### `w http.ResponseWriter`

Use `w` to write the response with Go's `net/http` APIs:

- `w.Header()` sets response headers, including `Content-Type` and `Set-Cookie`.
- `w.WriteHeader(status)` sets the HTTP status. Without an explicit status, the first body write sends `200`.
- `w.Write(body)` writes response body bytes.

Set headers before calling `WriteHeader` or writing the body. Use `http.Flusher` for [streaming](#streaming).

#### `r *http.Request`

Use `r` to read the incoming request:

| API                      | Behavior                                                                  |
| ------------------------ | ------------------------------------------------------------------------- |
| `r.Method`               | Read the HTTP method.                                                     |
| `r.PathValue("id")`      | Read a decoded dynamic parameter. Catch-all segments are joined with `/`. |
| `r.URL.Query()`          | Read query parameters, including repeated values.                         |
| `r.Header`, `r.Cookie()` | Read incoming headers and cookies after Next.js proxy processing.         |
| `r.Body`                 | Read the streamed request body.                                           |
| `r.Context().Done()`     | Observe cancellation when the client disconnects.                         |

In development and self-hosted deployments, Next.js selects the handler after routing, rewrites, and [`proxy.ts`](/docs/app/api-reference/file-conventions/proxy) processing. The handler receives the final destination URL, including its query and any `basePath`. For example, `/alias?sort=asc` rewritten to `/users/123` reaches Go as `/users/123?sort=asc`. `r.URL`, `r.RequestURI`, and dynamic parameters reflect that destination.

### `ParamValues`

Next.js generates a helper in the route package for reading individual decoded parameter values:

```go highlight={10} title="app/blog/[...slug]/route.go"
package route

import (
  "encoding/json"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(ParamValues(r, "slug"))
}
```

`ParamValues(r, name)` returns a `[]string`. It returns one value for a single dynamic segment, individual values for a catch-all segment, and `nil` for an absent parameter.

| Route                           | URL             | `r.PathValue("slug")` | `ParamValues(r, "slug")` |
| ------------------------------- | --------------- | --------------------- | ------------------------ |
| `app/items/[slug]/route.go`     | `/items/a`      | `"a"`                 | `[]string{"a"}`          |
| `app/blog/[...slug]/route.go`   | `/blog/a/b`     | `"a/b"`               | `[]string{"a", "b"}`     |
| `app/blog/[...slug]/route.go`   | `/blog/a%2Fb/c` | `"a/b/c"`             | `[]string{"a/b", "c"}`   |
| `app/blog/[[...slug]]/route.go` | `/blog`         | `""`                  | `nil`                    |

Use `ParamValues` when you need to distinguish an encoded slash within a segment from the separator between catch-all segments.

### Handler Convention

Each route directory is an ordinary Go package, such as `package route`. It cannot be `package main`: Next.js generates the program entrypoint and imports the route directory as a package. HTTP method functions must be declared in `route.go`; functions declared only in sibling `.go` files are not registered as handlers. Next.js generates method dispatch in the route package. Do not create `zz_next_route_*.go` files, which are reserved for generated code.

Sibling `.go` files compile together with `route.go` and must use the same package name. Handlers in `route.go` can call helpers declared in those files. Go applies its normal file selection to the route package, including build constraints, platform filename suffixes, and excluding `_test.go` files. Files that Go excludes, such as a `//go:build ignore` generator, can use any package name, including `main`. Shared packages can use ordinary module imports, including `internal` packages that are visible from the route directory, such as `<module>/internal/...` or `<module>/app/internal/...` for a route under `app`.

Direct `go run` and `go test` do not inject the generated wrapper or `ParamValues` helper. Run the route through Next.js to test its integration. Brackets, parentheses, and other characters in route directory names do not need to form valid Go import paths: Next.js compiles the route package from a virtual directory and reports errors and stack traces against the original files. For the same reason, embedding a `.go` file from the route directory itself with `go:embed` yields its source preceded by a `//line` directive. A route without a `go.mod` in its directory or a parent directory within the project uses the language version of the installed Go toolchain.

`next build` compiles all route directories into one executable, with or without an adapter, and `next start` runs it as one process that serves every Go Route Handler. The executable is one Go program with one main module, so every route directory must belong to the same Go module, or none of them may have a `go.mod`. A compile error in any Go route fails the build for all of them. Each route directory remains a separate package, so package-level names in different routes do not conflict, and each route can import the same `internal` packages as in development, including routes inside an `internal` directory. `next dev` compiles each route on its own, so an edit recompiles only that route.

Because every route shares one process in production, process-wide state is shared too. Package initialization (`init` functions and package-level variables) of every route runs when the Go server process starts, using its runtime environment. Shared packages initialize once per process. Registrations that must be unique per process, such as patterns on `http.DefaultServeMux`, `flag` definitions, or metrics in a global registry, conflict when two routes make the same one. Keep such state inside each route's handlers, or register it once in a shared package. Initialization failures surface at server startup and affect every Go route. `next build` compiles the executable without running package initialization, so configuration used only during initialization can be supplied at runtime.

Go routes support `app`, `src/app`, [route groups](/docs/app/api-reference/file-conventions/route-groups), and [dynamic segments](/docs/app/api-reference/file-conventions/dynamic-routes). A Go handler cannot share its URL with another Route Handler or page.

### Development and Errors

Turbopack tracks route sources, sibling files, local imported packages, module metadata, and embedded assets. Edits trigger recompilation. Compiler failures produce errors instead of serving the previous successful executable. Fixing the source allows later requests to recover.

Unchanged requests reuse the compiled process. After a rebuild, new requests use the replacement while in-flight requests can finish on the previous process for a limited time. If a process exits unexpectedly, active requests fail and later requests restart it. In production, one process serves every Go route, so its exit affects all of them. In development, a startup failure remains cached until the source changes or the server restarts. In production, a later request retries a failed startup.

A handler panic aborts its HTTP connection. An error response can be sent only if response headers have not already been sent.

## Examples

### Cookies

Read cookies with `r.Cookie` and set them with `http.SetCookie` before writing the response:

```go highlight={10,17} title="app/api/cookies/route.go"
package route

import (
  "fmt"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  theme := "light"
  if cookie, err := r.Cookie("theme"); err == nil {
    theme = cookie.Value
  }
  fmt.Fprint(w, theme)
}

func POST(w http.ResponseWriter, r *http.Request) {
  http.SetCookie(w, &http.Cookie{
    Name: "theme",
    Value: "dark",
    Path: "/",
    HttpOnly: true,
    SameSite: http.SameSiteLaxMode,
  })
  w.WriteHeader(http.StatusNoContent)
}
```

To delete a cookie, set a cookie with the same name and path and a negative `MaxAge`.

### Headers

Read request headers with `r.Header.Get` and set response headers with `w.Header().Set`:

```go highlight={10,11} title="app/api/headers/route.go"
package route

import (
  "fmt"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  w.Header().Set("Vary", "Accept-Language")
  fmt.Fprint(w, r.Header.Get("Accept-Language"))
}
```

Use `w.Header().Add` to append multiple values, including multiple `Set-Cookie` headers.

### Redirects

Use `http.Redirect` with the destination and status:

```go highlight={6} title="app/api/redirect/route.go"
package route

import "net/http"

func GET(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}
```

### Dynamic Route Segments

Use `r.PathValue` to read a [dynamic segment](/docs/app/api-reference/file-conventions/dynamic-routes):

```go highlight={9} title="app/items/[slug]/route.go"
package route

import (
  "fmt"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Item %s", r.PathValue("slug"))
}
```

For `/items/a`, `r.PathValue("slug")` returns `"a"`. For catch-all and optional catch-all routes, see [`ParamValues`](#paramvalues).

### URL Query Parameters

Use `r.URL.Query()` to read query parameters. `Get` returns the first value; indexing the map returns all values for that key.

```go highlight={9,12,13} title="app/api/search/route.go"
package route

import (
  "encoding/json"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  query := r.URL.Query()
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(map[string]any{
    "query": query.Get("query"),
    "tags": query["tag"],
  })
}
```

For `/api/search?query=hello&tag=go&tag=next`, the response contains `"query": "hello"` and `"tags": ["go", "next"]`.

### Streaming

Write and flush each response chunk with `http.Flusher`. Observe the request context to stop work when the client disconnects:

```go highlight={10,22,28} title="app/api/stream/route.go"
package route

import (
  "fmt"
  "net/http"
  "time"
)

func GET(w http.ResponseWriter, r *http.Request) {
  flusher, ok := w.(http.Flusher)
  if !ok {
    http.Error(w, "Streaming unavailable", http.StatusInternalServerError)
    return
  }

  w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  ticker := time.NewTicker(200 * time.Millisecond)
  defer ticker.Stop()

  for i := 0; i < 3; i++ {
    select {
    case <-r.Context().Done():
      return
    case <-ticker.C:
      if _, err := fmt.Fprintf(w, "Chunk %d\n", i+1); err != nil {
        return
      }
      flusher.Flush()
    }
  }
}
```

Deployment platforms may apply their own buffering and timeout limits.

### Request Body

Decode a JSON request body with `json.NewDecoder`:

```go highlight={13} title="app/items/route.go"
package route

import (
  "encoding/json"
  "net/http"
)

func POST(w http.ResponseWriter, r *http.Request) {
  var item struct {
    Name string `json:"name"`
  }
  r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
  if err := json.NewDecoder(r.Body).Decode(&item); err != nil {
    http.Error(w, "Invalid request body", http.StatusBadRequest)
    return
  }
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(item)
}
```

`http.MaxBytesReader` limits the number of request body bytes read by the handler.

### Request Body FormData

Use `r.ParseMultipartForm` to read multipart form data. Its argument limits the file data held in memory; use `http.MaxBytesReader` to limit the total request body size.

```go highlight={7,12} title="app/api/form/route.go"
package route

import "net/http"

func POST(w http.ResponseWriter, r *http.Request) {
  r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
  if err := r.ParseMultipartForm(1 << 20); err != nil {
    http.Error(w, "Invalid form data", http.StatusBadRequest)
    return
  }
  defer r.MultipartForm.RemoveAll()
  name := r.FormValue("name")
  w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  w.Write([]byte(name))
}
```

For URL-encoded forms, use `r.ParseForm` instead.

### CORS

Set CORS headers on the response. Define `OPTIONS` explicitly when a preflight response needs these headers; the automatic `OPTIONS` response only supplies `Allow`.

```go highlight={9,14} title="app/api/cors/route.go"
package route

import (
  "fmt"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  setCORSHeaders(w)
  fmt.Fprint(w, "Hello from Go!")
}

func OPTIONS(w http.ResponseWriter, r *http.Request) {
  setCORSHeaders(w)
  w.WriteHeader(http.StatusNoContent)
}

func setCORSHeaders(w http.ResponseWriter) {
  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
}
```

To set CORS headers for multiple routes, use [Proxy](/docs/app/api-reference/file-conventions/proxy#cors) or [`next.config` headers](/docs/app/api-reference/config/next-config-js/headers#cors).

### Webhooks

Read the raw request body before verifying a webhook signature. JSON decoding can change the representation a provider signed.

```go highlight={10} title="app/api/webhook/route.go"
package route

import (
  "io"
  "net/http"
)

func POST(w http.ResponseWriter, r *http.Request) {
  r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
  body, err := io.ReadAll(r.Body)
  if err != nil {
    http.Error(w, "Invalid webhook body", http.StatusBadRequest)
    return
  }
  // Verify the provider's signature against body before processing the event.
  _ = body
  w.WriteHeader(http.StatusNoContent)
}
```

Go handlers read `r.Body` directly and do not use the Pages Router `bodyParser` configuration.

### Non-UI Responses

Set the content type and write the response body to return XML or other non-UI content:

```go highlight={9} title="app/rss.xml/route.go"
package route

import (
  "fmt"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
  fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><channel>
  <title>My Blog</title>
  <link>https://example.com</link>
  <description>Latest posts</description>
</channel></rss>`)
}
```

### Sharing Response Logic

Method functions can call an unexported helper while setting different response statuses:

```go highlight={9,13} title="app/users/[id]/route.go"
package route

import (
  "fmt"
  "net/http"
)

func GET(w http.ResponseWriter, r *http.Request) {
  writeUser(w, r, http.StatusOK)
}

func POST(w http.ResponseWriter, r *http.Request) {
  writeUser(w, r, http.StatusCreated)
}

func writeUser(w http.ResponseWriter, r *http.Request, status int) {
  w.WriteHeader(status)
  fmt.Fprintf(w, "User %s", r.PathValue("id"))
}
```

### Segment Config Options

Like the [`maxDuration`](/docs/app/api-reference/file-conventions/route-segment-config/maxDuration) export in `route.ts`, `route.go` can declare a package-level `MaxDuration`:

```go title="app/api/route.go"
const MaxDuration = 30
```

`MaxDuration` is a positive integer literal in seconds, declared as a `const` or `var`, untyped or with an integer type such as `int`. A `time.Duration` type is a build error, because Go reads `30` as 30 nanoseconds there. Only `route.go` itself is read, statically: calls, references to other values, arithmetic, and environment reads are build errors. The deprecated `preferredRegion` option is not supported.

Go Route Handlers always execute dynamically. JavaScript exports such as `dynamic`, `revalidate`, `fetchCache`, and `runtime` do not configure Go handlers. ISR, `generateStaticParams`, Server Actions, and React execution are unsupported for Go routes.

## Deployment

For self-hosting, use Turbopack `next build` and `next start`. Copy the complete `.next` output when relocating a build on the same operating system and architecture, preserving executable permissions under `.next/server`. Each native descriptor has a `.native.json.nft.json` trace listing the shared executable.

[`output: 'standalone'`](/docs/app/api-reference/config/next-config-js/output) copies the shared Go executable into `.next/standalone` with its permissions, so `node .next/standalone/server.js` serves Go routes without a Go toolchain. The standalone output targets the operating system and architecture of the build machine.

Go Route Handlers have no build-time prerendering mode, so they cannot produce static response files for [`output: 'export'`](/docs/app/guides/static-exports#route-handlers).

Adapter deployments require an adapter that supports `runtime: 'go'`. Adapter builds compile every Go Route Handler into one executable, and all Go route outputs share its `filePath`. The platform selects the output for each request through the `x-matched-path` header, even when each output has its own process. Requests cannot select another compiled handler by their pathname. The platform must set `x-matched-path` and remove any value the client sent; otherwise a client could select any Go output. With `next start`, Next.js routes each request, replaces any client-sent `x-matched-path` with the selected route's exact path, and authenticates the request to the Go process. See [Go adapter outputs](/docs/app/api-reference/adapters/output-types#app-routes-outputsapproutes) and [invoking Go entrypoints](/docs/app/api-reference/adapters/invoking-entrypoints#go-runtime-runtime-go) for packaging and the HTTP server contract. Deployment platforms own routing, rewrites, and proxy execution. Work after the response completes has no completion guarantee.

## Build and Runtime Limitations

- WebSocket upgrades and HTTP trailers are unsupported.
- Adapter builds reject a Go route that the `x-matched-path` header cannot select as itself, such as `app/index/docs/route.go`, which is read as `/docs`, a path containing `?` or `#`, or a literal folder such as `%5Bid%5D` beside the `[id]` route it spells. Every production build rejects a folder name that ends with a space or contains a control character. `next dev` warns about both.
- Runtime file reads are not traced. Use `go:embed` for assets shipped with Go handlers.
- Go handlers read the process environment. `next.config` environment inlining does not apply.
- Go builds target the build host operating system and architecture with CGO disabled. The build environment must match the deployment runtime.
- Dependencies must build with CGO disabled and already be downloaded into the selected toolchain's module cache. Builds do not download dependencies or modify `go.sum`; the only `go.mod` changes Next.js makes are the `next/go` requirement and replacement.
- Go workspaces, versioned module replacements, directory replacements outside `turbopack.root`, vendoring, source symlinks, and cross-compilation are unsupported. Directory replacements inside it, such as the `next/go` mapping, are supported.
- The same experiment enables [`proxy.go`](/docs/app/api-reference/file-conventions/proxy-go). Go Pages API routes, `page.go`, and `layout.go` are unsupported.

Go routes support Turbopack's filesystem cache and Go's build cache. Unchanged executables can be reused across server or build processes. Source files, dependencies, embedded assets, generated wrappers, toolchain settings, and compilation targets participate in invalidation.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/docs/llms.txt](/docs/llms.txt)