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.
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 deviteration loop - The standard library's
net/httpis 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 startandoutput: '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.
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 theTURBOPACK_GOenvironment 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-domAdd dev, build, and start to the scripts in 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.
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.
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 aspackage route(the directory is treated as a library package that other packages canimport). Usingpackage maincauses a compile error - Declare top-level functions corresponding to HTTP methods (
GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS) directly inroute.gowith the signaturefunc(w http.ResponseWriter, r *http.Request) - Other
.gofiles 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 inroute.go - Don't create
zz_next_route_*.gofiles, as they are reserved for Next.js code generation
Start the development server to check that it works.
npm run devIf 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):
✓ goRoutesFrom another terminal, send a request to /api/hello with curl.
curl -i http://localhost:3000/api/helloYou 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.
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.
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 theParamValues(r, "slug")helper that Next.js generates - Reading the query parameter:
r.URL.Query().Get("format")checks for?format=textand switches the response format to plain text - Limiting the request body size:
http.MaxBytesReadersets an upper limit on the body to read (1 MiB here) before decoding it withjson.NewDecoder - Handling concurrent requests: Go's
net/httphandles each request concurrently in its own goroutine, so reads and writes to the sharednotesmap are protected with async.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 foundCalling 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.
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].
"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 buildWhen 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 demandLooking 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 startOnce 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.
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/httpby placingroute.gounder the App Router once you enableexperimental.goRoutes: true route.gois declared with a package name other thanmain, such aspackage routerather thanpackage main, and top-level functions likeGETandPOSTare defined directly in it- Dynamic segments are read with
r.PathValueand query parameters withr.URL.Query(), and Go handlers can coexist with TypeScriptroute.tsfiles and React pages in the same application next devautomatically recompiles only the changed route, whilenext buildcombines allroute.gofiles 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
Native Languages in Next.js | Next.js Blog
Next.js 16.5 | Next.js Blog
File-system conventions: route.go | Next.js Documentation
PR #101898: Go routes: compile route.go/proxy.go directories as importable packages, not package main
PR #101985: Go routes: compile all route.go handlers into one binary for production builds
PR #102362: Support output: 'standalone' with experimental.goRoutes





