← Homework · · 10 MIN
Forward Cookies from Next.js Server Components to a Go API
Why your Go API gets no session cookie from Next.js Server Components, and how to forward it, set it on login and call Go from the browser safely.
Your user is logged in. The browser has the session cookie. Your Next.js Server Component calls the Go API, and the Go API answers 401 Unauthorized.
Nothing is broken. A fetch from a Server Component is a brand new HTTP request made by your Next.js server, and the browser's cookies are not part of it. Next.js does not forward them for you. You have to read the cookie from the incoming request and attach it to the outgoing one yourself.
My stack is Next.js on the front and Go behind it, so this is a setup I care about. Most guides on this topic cover the Next.js half and stop. This one covers the whole path: forwarding the cookie, the Go middleware that reads it, logging in through a Server Action, and calling the Go API straight from the browser. The examples use the Next.js 15 App Router and Go's standard net/http package.
Why the cookie goes missing
There are two different kinds of requests in an App Router app, and cookies behave differently in each.
From the browser (a Client Component calling fetch): the browser attaches cookies automatically, as long as the cookie's domain, path and SameSite rules allow it, and the request uses credentials: "include" when it goes to another origin.
From the server (a Server Component, Server Action or Route Handler calling fetch): the request starts on your Next.js server. It is effectively a back-end service talking to another back-end service. There is no browser involved, so there are no cookies unless you add them.
Once you see it that way, the fix is clear: in server code, copy the session from the user's request into your request to Go.
Step 1: forward the session cookie from a Server Component
In Next.js 15, cookies() from next/headers returns a promise, so await it:
// app/dashboard/page.tsx
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
const API_URL = process.env.API_URL; // e.g. http://localhost:8080
export default async function DashboardPage() {
const session = (await cookies()).get("session")?.value;
if (!session) redirect("/login");
const res = await fetch(`${API_URL}/me`, {
headers: { Cookie: `session=${session}` },
cache: "no-store",
});
if (res.status === 401) redirect("/login");
if (!res.ok) throw new Error(`API error ${res.status}`);
const user: { name: string } = await res.json();
return <h1>Welcome back, {user.name}</h1>;
}
A few details matter:
- Forward only what the API needs. Passing one named cookie is safer than passing everything. If you do want to forward all of them,
(await cookies()).toString()gives you the fullCookieheader value. cache: "no-store"makes it explicit that this response is per user and must never be shared. Readingcookies()already makes the route render dynamically, which is exactly what you want for a page that depends on who is logged in.- Keep
API_URLserver-side. Without theNEXT_PUBLIC_prefix it never reaches the browser, so your Go service can live on a private network address.
Put it in one helper
Every page that talks to Go needs the same lines, so wrap them:
// lib/api.ts
import "server-only";
import { cookies } from "next/headers";
export async function api(path: string, init: RequestInit = {}) {
const session = (await cookies()).get("session")?.value;
const headers = new Headers(init.headers);
if (session) headers.set("Cookie", `session=${session}`);
return fetch(`${process.env.API_URL}${path}`, { ...init, headers, cache: "no-store" });
}
import "server-only" makes the build fail if a Client Component ever imports this file, which protects you from leaking server-only code into the browser.
Step 2: read the cookie in Go
On the Go side, a middleware reads the cookie, validates the session and puts the user in the request context:
package api
import (
"context"
"net/http"
)
type ctxKey string
const userKey ctxKey = "user"
func RequireSession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("session")
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
userID, err := validateSession(r.Context(), c.Value)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), userKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
validateSession is wherever your session logic lives: a lookup in PostgreSQL or Redis for opaque session IDs, or signature and expiry checks for a signed token. The middleware does not care whether the request came from a browser or from your Next.js server. Both send a normal Cookie header, so one code path handles both.
Wire it up on the routes that need a user:
mux := http.NewServeMux()
mux.HandleFunc("POST /login", handleLogin)
mux.Handle("GET /me", RequireSession(http.HandlerFunc(handleMe)))
The method and path patterns like "GET /me" need Go 1.22 or newer.
Step 3: log in through a Server Action
Logging in is the opposite direction: Go creates the session, and the browser needs to end up with the cookie. If the Next.js server calls Go's login endpoint, any Set-Cookie header that Go sends back lands on the Next.js server, not in the browser.
The cleanest fix is to have Next.js set the cookie itself. Go's login handler returns the session ID in the response body for this server-to-server call, and a Server Action stores it:
// app/login/actions.ts
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export async function login(_prev: unknown, formData: FormData) {
const res = await fetch(`${process.env.API_URL}/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: formData.get("email"),
password: formData.get("password"),
}),
cache: "no-store",
});
if (!res.ok) return { error: "Invalid email or password" };
const { session, expiresIn } = await res.json();
(await cookies()).set("session", session, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: expiresIn, // seconds
});
redirect("/dashboard");
}
Three settings on that cookie are doing real security work:
httpOnlykeeps JavaScript in the page from reading the session, which limits the damage of an XSS bug.securesends it only over HTTPS. It is switched off in development so the cookie still works onhttp://localhost.sameSite: "lax"stops the cookie from being sent on most cross-site requests, a solid default against CSRF.
One rule to remember: Server Components can read cookies, but they cannot set them. Setting has to happen in a Server Action, a Route Handler or middleware, because those run before the response headers are sent.
If you would rather keep Go in charge of the cookie format, you can relay Go's header instead: res.headers.getSetCookie() returns each Set-Cookie value, and you parse and re-set them with cookies().set. It works, but it is more code to get right than returning the session in the body.
Step 4: calling the Go API from the browser
Sometimes a Client Component needs to call Go directly, for example for live search or uploads, without a round trip through Next.js. Now the browser sends the cookie itself, so the question becomes whether it is allowed to.
If the frontend and API are on different origins, for example app.example.com and api.example.com, you need three things.
1. The fetch must ask for credentials:
const res = await fetch("https://api.example.com/search?q=go", {
credentials: "include",
});
2. Go must allow your exact origin, with credentials:
func CORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Origin") == "https://app.example.com" {
w.Header().Set("Access-Control-Allow-Origin", "https://app.example.com")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
Browsers reject a wildcard Access-Control-Allow-Origin: * when credentials are included, so the header has to name the origin.
3. The cookie must be shared with the API's domain. A cookie set on app.example.com is not sent to api.example.com. Set it with domain: ".example.com" so both subdomains receive it. Because the two subdomains belong to the same site, sameSite: "lax" still works. If the frontend and API live on completely different domains, the cookie needs sameSite: "none" with secure: true, and browsers that block third-party cookies may refuse it anyway.
That last point is the strongest argument for the simpler setup: keep browser traffic going through Next.js (a Route Handler or the rewrites option in next.config), so the browser only ever talks to one origin and the cookie never has to cross domains.
Protecting pages in Next.js middleware
You can redirect logged-out users before a page even renders:
// middleware.ts
import { NextResponse, type NextRequest } from "next/server";
export function middleware(req: NextRequest) {
if (!req.cookies.has("session")) {
return NextResponse.redirect(new URL("/login", req.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*"] };
This only checks that a cookie exists. It is a fast first gate for a better experience, and it does not replace validation: anyone can create a cookie called session. The Go middleware from Step 2 is what actually decides whether a request is allowed.
Cookies or bearer tokens?
Both work with a Go API. This is how they compare for a Next.js site:
| httpOnly session cookie | Bearer token | |
|---|---|---|
| Sent by | The browser, automatically | Your code, in the Authorization header |
| Readable by page scripts | No | Yes, wherever you store it |
| Server Components | Forward it with cookies() | Read it from wherever you stored it, then attach it |
| Cross-site request risk | Needs SameSite or CSRF protection | Not sent automatically, so lower |
| Best for | Websites | Mobile apps and service-to-service calls |
Troubleshooting checklist
If Go still answers 401, check these in order:
- Log the incoming
Cookieheader in Go. If it is empty, the problem is on the Next.js side. - Server fetch: are you attaching the cookie in the request headers? Server-side fetches never do it automatically.
- Browser fetch: is
credentials: "include"set, and does Go returnAccess-Control-Allow-Credentials: truewith your exact origin? - Cookie scope: does the cookie's
domainandpathcover the API's URL? securein development: asecurecookie is not stored or sent over plainhttp://, so login can silently fail onlocalhost.- Expired session: a stale cookie can still be sent; check expiry in
validateSession.
Frequently asked questions
Why doesn't Next.js forward cookies in server-side fetch?
Because the request is made by your server, not the user's browser. Next.js cannot know which of the user's cookies a third-party API should receive, so it sends none. Read the ones you need with cookies() and add them to the request headers.
Can I set cookies in a Next.js Server Component?
No. Server Components can read cookies but not set them. Use a Server Action, a Route Handler or middleware to set or delete cookies.
Should my Go API use cookies or a bearer token?
For a website, an httpOnly cookie is usually the safer choice because page scripts cannot read it. Bearer tokens in an Authorization header suit mobile apps and service-to-service calls. A Go middleware can accept both if you need to support both kinds of clients.
Why does my cookie work locally but not in production?
The usual causes are a missing domain when the API is on a different subdomain, a SameSite value that blocks the request, or CORS returning a wildcard origin. Compare the cookie's attributes in the browser's DevTools with the API's URL.
Does reading cookies make my Next.js page dynamic?
Yes. Calling cookies() opts the route into dynamic rendering, so it runs on every request. For pages that depend on the logged-in user that is correct, since their content cannot be shared between visitors.
Wrapping up
Most cookie trouble between Next.js and Go comes from one mental model: a Server Component fetch is a server talking to a server. Forward the session explicitly, set cookies only where Next.js allows it, keep Go as the place where sessions are actually validated, and route browser calls through one origin when you can.
I wrote about the lessons from building the Go side of authentication in What Building Authentication in Go Taught Me About Security. More posts are on the Writing page.