This article was translated from Japanese by AI and may contain inaccuracies. For the most accurate content, please refer to the original Japanese version.
厚切り牛タンのイラスト

Trying Out Go Route Handlers (route.go) in Next.js

Go Route Handlers (route.go), introduced experimentally in Next.js 16.5, let you place Go net/http-based API endpoints directly under the App Router. This article walks through trying Go Route Handlers hands-on.

Until now, Next.js has been designed around a single stack: everything from UI rendering and server rendering to API endpoints is written in TypeScript / JavaScript and runs on Node.js. This single-language, single-runtime setup is highly productive for most applications. However, when you wanted to write things like high-throughput webhook receivers, streaming proxies, or CPU-intensive data processing in a compiled language, you had to set up a separate microservice along with its own build and deployment pipeline.

Next.js 16.5, released on December 2, 2026, introduces Go Route Handlers as an experimental feature that extends this single-language setup. It lets you write API endpoints in Go while following App Router conventions.

In this article, I'll show what it looks like to actually run Go Route Handlers.

Note

As of December 3, 2026, Go Route Handlers (experimental.goRoutes) are an experimental feature and are not recommended for production use. The API and configuration format may change in future releases.

What Are Go Route Handlers?

Go Route Handlers let you define API endpoints using net/http from the Go standard library by placing a route.go file instead of a route.ts file in the Next.js App Router (the app/ directory). React rendering, Server Actions, and existing Route Handlers continue to run on Node.js as before; only the endpoints written in route.go are compiled into a native executable.

In Native Languages in Next.js, the Next.js team explains why they decided to add native language support now: the spread of coding agents has shifted the trade-offs. Previously, adopting a second language meant a heavy cost for the whole team in context switching and maintenance. Coding agents have lowered the burden of writing, testing, and maintaining Go code, leaving the operational overhead of managing separate services and pipelines as the main barrier. The move also extends to the runtime the toolchain nativization that Next.js 16.x has been pursuing, such as Turbopack (Rust) and TypeScript 7's Go-based type checking.

The official blog lists four reasons why Go was chosen as the first supported language, as one that fits the constraints of both the development experience and production execution:

  • Incremental builds are fast, so they don't get in the way of the next dev iteration loop
  • The standard library's net/http is stable and widely known to both developers and coding agents, so you can write handlers without adopting a separate web framework
  • It compiles to a static binary with no runtime dependencies, which makes it easy to integrate with next start and output: 'standalone'. Go's built-in cross-compilation also makes it easier to target different deployment architectures in future releases
  • Its networking stack and low memory footprint suit both API routes and the Next.js server itself

Note that native language support isn't meant to be limited to Go. The official blog states that Go is just the first supported language, and that the plan is to expand to other native languages, including Rust.

Note

In a production workload benchmark reported on the official blog, cumulative active CPU time dropped by 81%, from 23.412 seconds with route.ts to 4.546 seconds with route.go.

Setup

From here, we'll set up an actual Next.js 16.5 project and run Go Route Handlers. To run Go Route Handlers, you need to meet the following two prerequisites (route.go API Reference):

  • Put Go 1.24 or later on your PATH, or specify the path to the executable with the TURBOPACK_GO environment variable
  • Use Turbopack as the bundler

Creating and Configuring the Project

Create a new directory and install Next.js 16.5.0, React, and TypeScript.

mkdir nextjs-go-routes
cd nextjs-go-routes
npm init -y
npm install [email protected] [email protected] [email protected]
npm install -D typescript @types/node @types/react @types/react-dom

Add dev, build, and start to the scripts in package.json.

package.json
{
  "name": "nextjs-go-routes",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "^16.5.0",
    "react": "^19.3.1",
    "react-dom": "^19.3.1"
  },
  "devDependencies": {
    "@types/node": "^22.20.7",
    "@types/react": "^19.3.3",
    "@types/react-dom": "^19.3.0",
    "typescript": "^5.9.3"
  }
}

Next, create next.config.ts and enable experimental.goRoutes.

next.config.ts
import type { NextConfig } from "next";
 
const nextConfig: NextConfig = {
  experimental: {
    goRoutes: true,
  },
};
 
export default nextConfig;

For a minimal setup that only uses the Go standard library, you don't need a go.mod; handlers are compiled with the version of the installed Go toolchain. If you want to import external packages or the Go SDK packages provided by Next.js (such as next/go/proxy), run go mod init example.com/app at the project root to set up a Go module. Note that Next.js builds don't download external dependencies automatically and don't update go.sum, so you need to fetch external packages into the module cache beforehand with something like go get.

Running a Minimal route.go

First, let's create a minimal Go Route Handler that returns JSON for GET /api/hello. Put the following code in app/api/hello/route.go.

app/api/hello/route.go
package route
 
import (
	"encoding/json"
	"net/http"
	"runtime"
)
 
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!",
		"goVersion": runtime.Version(),
	})
}

Writing route.go follows these conventions:

  • Declare the package with a name other than main, such as package route (the directory is treated as a library package that other packages can import). Using package main causes a compile error
  • Declare top-level functions corresponding to HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) directly in route.go with the signature func(w http.ResponseWriter, r *http.Request)
  • Other .go files in the same directory are compiled together as part of the same package, so you can split out helper functions. However, the HTTP method functions themselves must be written in route.go
  • Don't create zz_next_route_*.go files, as they are reserved for Next.js code generation

Start the development server to check that it works.

npm run dev

If goRoutes appears under Experiments in the startup log, the feature is enabled.

▲ Next.js 16.5.0 (Turbopack)
- Local:         http://localhost:3000
✓ Ready in 322ms
- Experiments (use with caution):
  ✓ goRoutes

From another terminal, send a request to /api/hello with curl.

curl -i http://localhost:3000/api/hello

You get 200 OK and JSON containing the Go runtime version, as shown below.

HTTP/1.1 200 OK
content-type: application/json
...
 
{"goVersion":"go1.27.4","message":"Hello from Go!"}

route.go also supports automatic recompilation. If you edit and save the code while next dev is running, Turbopack detects the change and recompiles only that route. The updated response is returned from the next request onward, without restarting the server.

Coexisting with TypeScript Route Handlers

Let's also confirm that a traditional TypeScript Route Handler can live alongside it in the same application, with both Go and Node.js working. Create app/api/node-info/route.ts.

app/api/node-info/route.ts
import { NextResponse } from "next/server";
 
export function GET() {
  return NextResponse.json({
    runtime: "node",
    nodeVersion: process.version,
  });
}

When you send requests to both /api/hello and /api/node-info, Go and Node.js each respond from the same development server.

$ curl http://localhost:3000/api/hello
{"goVersion":"go1.27.4","message":"Hello from Go!"}
 
$ curl http://localhost:3000/api/node-info
{"runtime":"node","nodeVersion":"v24.21.0"}

Note that, following the same convention as route.ts, a single URL path cannot have both route.go and another Route Handler or a page.tsx.

Handling Dynamic Routes and POST Requests

Next, let's build an API for saving and retrieving notes that combines an App Router dynamic segment ([id]), a query parameter, and a JSON request body. Add app/api/notes/[id]/route.go, which stores a note for the given ID in memory with POST and reads it back with GET.

app/api/notes/[id]/route.go
package route
 
import (
	"encoding/json"
	"net/http"
	"sync"
	"time"
)
 
type note struct {
	ID        string `json:"id"`
	Title     string `json:"title"`
	Body      string `json:"body"`
	UpdatedAt string `json:"updatedAt"`
}
 
type noteInput struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}
 
var (
	mu    sync.RWMutex
	notes = map[string]note{}
)
 
func GET(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
 
	mu.RLock()
	item, ok := notes[id]
	mu.RUnlock()
 
	if !ok {
		http.Error(w, "Note not found", http.StatusNotFound)
		return
	}
 
	if r.URL.Query().Get("format") == "text" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Write([]byte(item.Title + "\n\n" + item.Body + "\n"))
		return
	}
 
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(item)
}
 
func POST(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
 
	var input noteInput
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		http.Error(w, "Invalid JSON body", http.StatusBadRequest)
		return
	}
	if input.Title == "" {
		http.Error(w, "Title is required", http.StatusBadRequest)
		return
	}
 
	item := note{
		ID:        id,
		Title:     input.Title,
		Body:      input.Body,
		UpdatedAt: time.Now().UTC().Format(time.RFC3339),
	}
 
	mu.Lock()
	notes[id] = item
	mu.Unlock()
 
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(item)
}

There are four key points in this code:

  • Reading the dynamic segment: r.PathValue("id"), a standard API since Go 1.22, gives you the [id] part of the URL. For catch-all segments such as [...slug], r.PathValue("slug") returns the segments joined with /, so if you want the individual values as a []string, use the ParamValues(r, "slug") helper that Next.js generates
  • Reading the query parameter: r.URL.Query().Get("format") checks for ?format=text and switches the response format to plain text
  • Limiting the request body size: http.MaxBytesReader sets an upper limit on the body to read (1 MiB here) before decoding it with json.NewDecoder
  • Handling concurrent requests: Go's net/http handles each request concurrently in its own goroutine, so reads and writes to the shared notes map are protected with a sync.RWMutex

Use curl to check, in order, saving with POST, retrieving with GET (as JSON and as plain text), and the response to a GET for an unknown ID (404).

# Save a note with POST (201)
$ curl -i -X POST http://localhost:3000/api/notes/meeting \
  -H "Content-Type: application/json" \
  -d '{"title":"Weekly sync notes","body":"Continue evaluating Next.js 16.5"}'
HTTP/1.1 201 Created
content-type: application/json
...
 
{"id":"meeting","title":"Weekly sync notes","body":"Continue evaluating Next.js 16.5","updatedAt":"2026-12-03T11:23:34Z"}
 
# Retrieve the saved note as JSON with GET
$ curl http://localhost:3000/api/notes/meeting
{"id":"meeting","title":"Weekly sync notes","body":"Continue evaluating Next.js 16.5","updatedAt":"2026-12-03T11:23:34Z"}
 
# Retrieve it as plain text using the query parameter
$ curl "http://localhost:3000/api/notes/meeting?format=text"
Weekly sync notes
 
Continue evaluating Next.js 16.5
 
# Unknown ID (404)
$ curl -i http://localhost:3000/api/notes/unknown
HTTP/1.1 404 Not Found
content-type: text/plain; charset=utf-8
...
 
Note not found

Calling a Go Route Handler from a React Page

Next, let's add a minimal page that calls the /api/notes/[id] endpoint we just created from React. First, create app/layout.tsx as the root layout.

app/layout.tsx
import type { ReactNode } from "react";
 
export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

Then create app/page.tsx, which uses fetch to save (POST) and retrieve (GET) notes via /api/notes/[id].

app/page.tsx
"use client";
 
import { useState, type SyntheticEvent } from "react";
 
type Note = {
  id: string;
  title: string;
  body: string;
  updatedAt: string;
};
 
export default function HomePage() {
  const [id, setId] = useState("meeting");
  const [title, setTitle] = useState("Weekly sync notes");
  const [body, setBody] = useState("Continue evaluating Next.js 16.5");
  const [note, setNote] = useState<Note | null>(null);
  const [error, setError] = useState<string | null>(null);
 
  async function handleSave(event: SyntheticEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);
 
    try {
      const response = await fetch(`/api/notes/${encodeURIComponent(id)}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, body }),
      });
 
      if (!response.ok) {
        setNote(null);
        setError(await response.text());
        return;
      }
 
      const data: Note = await response.json();
      setNote(data);
    } catch {
      setNote(null);
      setError("Failed to save note");
    }
  }
 
  async function handleLoad() {
    setError(null);
 
    try {
      const response = await fetch(`/api/notes/${encodeURIComponent(id)}`);
 
      if (!response.ok) {
        setNote(null);
        setError(await response.text());
        return;
      }
 
      const data: Note = await response.json();
      setNote(data);
    } catch {
      setNote(null);
      setError("Failed to load note");
    }
  }
 
  return (
    <main>
      <h1>Next.js Go Routes</h1>
      <form onSubmit={handleSave}>
        <div>
          <label>
            ID{" "}
            <input
              type="text"
              value={id}
              onChange={(e) => setId(e.target.value)}
            />
          </label>
        </div>
        <div>
          <label>
            Title{" "}
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </label>
        </div>
        <div>
          <label>
            Body{" "}
            <input
              type="text"
              size={32}
              value={body}
              onChange={(e) => setBody(e.target.value)}
            />
          </label>
        </div>
        <div>
          <button type="submit">Save</button>{" "}
          <button type="button" onClick={handleLoad}>
            Load
          </button>
        </div>
      </form>
      {error && <p role="alert">{error}</p>}
      {note && <pre>{JSON.stringify(note, null, 2)}</pre>}
    </main>
  );
}

From the client's point of view, there's no need to care whether the endpoint is backed by route.ts or route.go; you can fetch /api/notes/${encodeURIComponent(id)} as usual. I was able to confirm it working in practice as well.

Checking the Build Behavior

Next, let's run a production build and see how Go Route Handlers are built and executed.

npm run build

When I ran it locally, the build completed as follows.

▲ Next.js 16.5.0 (Turbopack)
- Experiments (use with caution):
  ✓ goRoutes
 
  Creating an optimized production build ...
✓ Compiled successfully in 5.4s
✓ Finished TypeScript in 1953ms
✓ Collecting page data using 7 workers in 477ms
✓ Generating static pages using 7 workers (4/4) in 84ms
✓ Finalizing page optimization in 12ms
 
Route (app)
┌ ○ /
├ ○ /_not-found
├ ƒ /api/hello
├ ƒ /api/node-info
└ ƒ /api/notes/[id]
 
○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand

Looking at the route list, / is statically generated (○), while all three API routes are treated as dynamic (ƒ). Note, however, that since Next.js 15, GET in route.ts also runs dynamically by default, so /api/node-info being ƒ isn't specific to Go Route Handlers. The difference is whether you can change it through configuration. A route.ts can be switched to static generation with route segment config such as export const dynamic = "force-static", whereas Go Route Handlers always execute dynamically and don't support ISR, generateStaticParams, JavaScript route segment config (such as dynamic or revalidate), or static export.

A Single Shared Binary

If you look under .next/server/ after the build, you'll see that only one Go executable has been generated.

ls -lh .next/server/go-routes-*
file .next/server/go-routes-*
cat .next/server/app/api/hello/route.native.json
cat '.next/server/app/api/notes/[id]/route.native.json'

The output is as follows.

-rwxr-xr-x@ 1 user  staff   8.8M Dec  3 20:22 .next/server/go-routes-514bfff808d4ae03a0073604defbf3cc
.next/server/go-routes-514bfff808d4ae03a0073604defbf3cc: Mach-O 64-bit executable arm64
{"executable":"go-routes-514bfff808d4ae03a0073604defbf3cc","goos":"darwin","goarch":"arm64","config":{},"route":"/api/hello"}
{"executable":"go-routes-514bfff808d4ae03a0073604defbf3cc","goos":"darwin","goarch":"arm64","config":{},"route":"/api/notes/[id]"}

While next dev recompiles per changed route, next build combines all route.go files into a single Go executable, and each route's route.native.json references that shared binary.

As the file output Mach-O 64-bit executable arm64 shows, the generated binary targets the OS and architecture of the machine that ran the build. Cross-compilation isn't supported at the moment, so if you build on macOS and deploy the output as-is to a Linux server, Go Route Handlers won't work. You need to build in an environment with the same OS and architecture as your deployment target (for example, in CI or a Docker container).

Builds also run with CGO disabled. CGO is Go's mechanism for calling C code (import "C"). Because it's disabled, packages that depend on C libraries, such as the SQLite driver github.com/mattn/go-sqlite3, can't be used from route.go; you need to pick a pure Go implementation such as modernc.org/sqlite instead. On the upside, the result is a static binary that doesn't depend on C libraries like libc, so it runs without installing any additional libraries in the runtime environment.

Running the Production Server

After the build, start the production server with npm run start.

npm run start

Once it's up, sending a request to /api/hello returns the same JSON as during development, this time from the compiled shared binary.

$ curl http://localhost:3000/api/hello
{"goVersion":"go1.27.4","message":"Hello from Go!"}

Since production runs the precompiled binary, you don't need the Go toolchain installed on the server.

Note

Native Languages in Next.js also introduces the next start --experimental-new-server option, which rewrites next start itself in Go and handles requests to route.go directly in Go without going through Node.js.

Summary

  • Go Route Handlers, introduced experimentally in Next.js 16.5, let you write API endpoints based on Go's net/http by placing route.go under the App Router once you enable experimental.goRoutes: true
  • route.go is declared with a package name other than main, such as package route rather than package main, and top-level functions like GET and POST are defined directly in it
  • Dynamic segments are read with r.PathValue and query parameters with r.URL.Query(), and Go handlers can coexist with TypeScript route.ts files and React pages in the same application
  • next dev automatically recompiles only the changed route, while next build combines all route.go files into a single shared executable
  • Go 1.24 or later and Turbopack are currently required, and Go handlers always execute dynamically
  • Cross-compilation isn't supported; the binary is built for the same OS and architecture as the build machine
  • Builds run with CGO disabled, so Go packages that depend on C libraries can't be used

References

Comprehension check

Answer the following questions to deepen your understanding of the article.

Which of the following matches the conventions for writing `route.go` described in the article?

  • Declare the package as `package main` and register `GET` and `POST` inside `func main()`

    Try again

    Using `package main` in `route.go` causes a compile error. You need a package name other than `main`, such as `package route`.

  • HTTP method functions are automatically recognized as routes even if they are written in a separate `.go` file in the same directory

    Try again

    You can split helper functions into other `.go` files in the same directory, but the HTTP method functions themselves must be written directly in `route.go`.

  • Declare the package with a name other than `main`, such as `package route`, and declare top-level functions corresponding to HTTP methods directly in `route.go`

    Correct!

    As listed in the article's conventions, you declare the package with a name other than `main` and write top-level functions such as `GET` and `POST` in `route.go` with the signature `func(w http.ResponseWriter, r *http.Request)`.

  • Place `route.go` and `route.ts` side by side at the same URL path and dispatch each method to Go or Node.js

    Try again

    Following the same convention as `route.ts`, a single URL path cannot have both `route.go` and another Route Handler or a `page.tsx`.

In `app/api/notes/[id]/route.go`, which combination of APIs is used to read the dynamic segment `[id]`, read the query parameter, and limit the request body size, respectively?

  • `r.PathValue("id")`, `r.URL.Query().Get("format")`, `http.MaxBytesReader`

    Correct!

    As in the article's implementation, the dynamic segment is read with `r.PathValue("id")`, the query parameter with `r.URL.Query().Get("format")`, and the body limit is set with `http.MaxBytesReader`.

  • `r.URL.Query().Get("id")`, `r.PathValue("format")`, `sync.RWMutex`

    Try again

    The roles of `r.PathValue` and `r.URL.Query().Get` are reversed, and `sync.RWMutex` is used to protect the shared `notes` map from concurrent requests.

  • `r.PathValue("id")`, `json.NewDecoder`, `runtime.Version()`

    Try again

    `json.NewDecoder` decodes the JSON body and `runtime.Version()` returns the Go runtime version; neither is used for query parameters or size limits.

  • `NextResponse.json`, `r.URL.Query().Get("format")`, `http.Error`

    Try again

    `NextResponse.json` is an API used in TypeScript `route.ts` files, and `http.Error` is a function for sending error responses.

Which of the following describes the behavior, as explained and verified in the article, when running `next dev` and `next build` on a project containing Go Route Handlers?

  • With `next dev`, you must manually restart the development server every time you change `route.go`

    Try again

    With `next dev`, Turbopack detects changes and recompiles only the modified route, so updated responses are returned without restarting the server.

  • With `next build`, `route.go` is also statically generated (`○`) and supports ISR and static export

    Try again

    Go Route Handlers always execute dynamically (`ƒ`) and do not support ISR, `generateStaticParams`, or static export.

  • With `next build`, a separate Go executable is generated for each `route.go` file

    Try again

    Per-route compilation happens in `next dev`; with `next build`, all `route.go` files are combined into a single shared executable.

  • With `next dev`, only the changed route is automatically recompiled, and with `next build`, all `route.go` files are combined into a single Go executable

    Correct!

    As verified in the article, `next dev` automatically recompiles per route, and `next build` combines all `route.go` files into one executable that each route's `route.native.json` references.