Connect a Next.js frontend to a Go backend
Your Go API answers curl and Postman perfectly, and the browser throws its response away. Then you fix that, the login returns 200, and the very next request is still unauthenticated. Both are the same subject, and neither is a bug in your code.
A browser enforces rules that no other HTTP client does, because a browser carries your users' credentials and is pointed at untrusted pages all day. This explains the three rules that matter, in the order you hit them, and ends with a configuration you can deploy.
18 min read. Commands and output last run against Grit v3.560.0.
What you will have at the end
A Go API a browser will read from, with the allowed origin coming from configuration.
A login whose cookie is actually sent back on the next request, in development across two ports and in production across two subdomains.
Enough understanding of SameSite to predict which of your deployments will break before it does.
An origin is scheme, host and port
Two URLs share an origin when all three match. These are all different origins from http://localhost:3000:
http://localhost:8080, because the port differs. This is the one that catches you in development.https://localhost:3000, because the scheme differs.http://127.0.0.1:3000, because the host string differs, even though it resolves to the same machine.https://api.example.comagainsthttps://example.com, because the host differs. Subdomains are separate origins.
That last one matters more than people expect: the common production layout, frontend on the apex and API on a subdomain, is cross-origin, so everything on this page applies in production and not only locally.
Rule one: the response is withheld unless the server allows it
Here is the error, as it appears in the console:
Access to fetch at 'http://localhost:8080/api/users' from origin'http://localhost:3000' has been blocked by CORS policy: No'Access-Control-Allow-Origin' header is present on the requested resource.
Read that carefully, because the wording hides what happened. The request was sent. Your server did run the handler. If it was a POST that created a row, the row exists. The browser received the response and refused to hand it to your JavaScript, because the response did not say which origins are allowed to read it.
So CORS is not a firewall and does not protect your API. It protects the user's other tabs: it is what stops a page on a random site reading your bank's API using your logged-in session. Authorisation is still entirely your job.
The preflight
For anything beyond a simple GET or form post, the browser asks permission first, with an OPTIONS request:
OPTIONS /api/users HTTP/1.1Origin: http://localhost:3000Access-Control-Request-Method: POSTAccess-Control-Request-Headers: content-type, authorization
Your server must answer that with the permissions and no body. If it instead runs your route handler, or returns a 404 because you only registered POST, the real request never happens. A Content-Type: application/json header is enough on its own to trigger a preflight, which is why it appears the moment you start sending JSON.
The middleware, written out
package middlewareimport ("net/http""strings""github.com/gin-gonic/gin")// CORS allows exactly the origins given, which come from configuration// rather than from this file.//// There is no wildcard branch on purpose. A browser refuses to send// credentials to a wildcard origin, so the moment cookies are involved the// wildcard silently stops working, and the failure looks like an auth bug// rather than a CORS one.func CORS(allowed []string) gin.HandlerFunc {set := make(map[string]bool, len(allowed))for _, o := range allowed {set[strings.TrimSpace(o)] = true}return func(c *gin.Context) {origin := c.GetHeader("Origin")if origin != "" && set[origin] {// Echo the caller's origin back. Not a list: the header takes// exactly one value, and browsers reject a comma-separated one.c.Header("Access-Control-Allow-Origin", origin)c.Header("Access-Control-Allow-Credentials", "true")// Caches key on this, so a response cached for one origin is not// served to another. Leaving it out is a real bug behind a CDN.c.Header("Vary", "Origin")}c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")// How long the browser may remember this answer, so it stops asking// before every request.c.Header("Access-Control-Max-Age", "600")if c.Request.Method == http.MethodOptions {c.AbortWithStatus(http.StatusNoContent)return}c.Next()}}
Register it before your routes, with the origins read from the environment:
r := gin.Default()r.Use(middleware.CORS(strings.Split(os.Getenv("CORS_ORIGINS"), ",")))// routes after this line
CORS_ORIGINS=http://localhost:3000# production:# CORS_ORIGINS=https://app.example.com,https://admin.example.com
Middleware registered after a route does not run for it
Gin builds the handler chain when the route is registered. A r.Use(...) below your r.GET(...) applies to nothing above it, and this is quiet: no error, no warning, just a route that behaves differently from its neighbours.
Rule two: cookies are not sent unless you ask
CORS is fixed, the login endpoint returns 200 and sets a cookie, and the next request is still unauthenticated. Three separate things have to be true, and missing any one of them produces exactly this.
The browser must be told to send credentials
By default fetch sends no cookies cross-origin, and attaches none from the response either. You opt in per request:
const res = await fetch(`${API}/auth/login`, {method: 'POST',credentials: 'include', // <- without this, nothing else mattersheaders: { 'Content-Type': 'application/json' },body: JSON.stringify({ email, password }),})
Set it once, in your API client, rather than on each call. A single fetch somewhere that forgets it is a bug that only shows up on one screen.
const API = process.env.NEXT_PUBLIC_API_URL!export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {const res = await fetch(`${API}${path}`, {...init,credentials: 'include',headers: { 'Content-Type': 'application/json', ...init.headers },})if (!res.ok) {const body = await res.json().catch(() => ({}))throw new Error(body?.error?.message ?? `request failed: ${res.status}`)}return res.json()}
The server must allow credentials, and name the origin
Access-Control-Allow-Credentials: true, which the middleware above sends, and not a wildcard origin. A browser refuses the combination of credentials: 'include' and Access-Control-Allow-Origin: * outright, and the console message talks about the wildcard rather than about your cookie, so the connection is easy to miss.
The cookie's own attributes must permit it
This is where most of the remaining time goes.
http.SetCookie(c.Writer, &http.Cookie{Name: "refresh_token",Value: token,Path: "/api/auth",HttpOnly: true, // JavaScript cannot read it, which is the pointSecure: cfg.Env == "production", // required whenever SameSite is NoneSameSite: sameSite, // see belowMaxAge: int(30 * 24 * time.Hour / time.Second),})
SameSite decides whether the browser attaches the cookie to a request triggered by a different site. The three values, and what each means for you:
Lax, the default in modern browsers. Sent on top-level navigation, not on a cross-sitefetch. This is why a cookie that exists in devtools is still not sent.Strict. Never sent cross-site at all, including when the user clicks a link from an email into your app, which logs them out at the worst moment.None. Always sent, and requiresSecure, which requires HTTPS. A browser silently drops aSameSite=Nonecookie that is notSecure.
There is one more rule nobody tells you: localhost:3000 and localhost:8080 are the same site, even though they are different origins. SameSite is judged on the registrable domain, which ignores the port. So a Lax cookie works fine across your two development ports, and then fails in production when the frontend and API are on different domains.
Pick by deployment, not by environment
If your frontend and API share a registrable domain in production, app.example.com and api.example.com, then Lax works and is the safer choice. If they are on genuinely different domains, you need None with Secure, and therefore HTTPS everywhere.
Deciding this from NODE_ENV rather than from the actual deployment is how a configuration works locally and in staging and fails in production.
Also set Domain=.example.com when the cookie must be readable across subdomains. Without it, a cookie set by api.example.com is not sent to app.example.com at all.
Rule three: server components are not in the browser
A Next.js server component runs on the server, where there is no browser, no ambient cookie jar and no CORS. Three consequences people trip over.
- CORS does not apply. A fetch from a server component to your Go API is server to server. If that one works and the client one does not, you have a CORS problem, and you have just proved it.
- Cookies are not attached automatically. You have to read them and forward them yourself.
localhostmay not mean the same thing. In Docker, the server component resolveslocalhostinside its own container. It needs the service name, while the browser needs the public URL. Two variables, not one.
import { cookies } from 'next/headers'export default async function Dashboard() {const jar = await cookies()const res = await fetch(`${process.env.API_URL_INTERNAL}/api/me`, {headers: { cookie: jar.toString() }, // forward it by handcache: 'no-store', // never cache a per-user response})const { data } = await res.json()return <h1>Hello {data.name}</h1>}
# What the browser calls. Must be public and reachable from outside.NEXT_PUBLIC_API_URL=http://localhost:8080# What the Next.js server calls. Inside Docker this is the service name.API_URL_INTERNAL=http://api:8080
NEXT_PUBLIC_ is compiled into the bundle
Any variable with that prefix is substituted at build time and shipped to the browser, where anyone can read it. It is right for an API URL and wrong for anything else. A secret with that prefix is a published secret, and the build will not warn you.
The alternative: make it same-origin
Everything above exists because the two are on different origins. You can simply not do that: have Next.js proxy /api through to Go, so the browser only ever talks to one origin.
const nextConfig = {async rewrites() {return [{source: '/api/:path*',destination: `${process.env.API_URL_INTERNAL}/api/:path*`,},]},}export default nextConfig
Now the browser fetches /api/users, same origin, no CORS, no credentials: 'include', no SameSite question. Cookies are first-party.
What it costs: every API request now goes through the Node process, which adds a hop and makes Node a bottleneck under load. Streaming responses and file uploads need care. And mobile or desktop clients cannot use the proxy, so the direct path has to work anyway.
A reasonable rule: proxy if the web app is the only client, go direct with proper CORS if there will be others.
When it goes wrong
No 'Access-Control-Allow-Origin' header is present on the requested resource
The server did not send the header. Three things to check in order: that the middleware is registered before the routes; that the origin in CORS_ORIGINS matches exactly, including scheme and port and with no trailing slash; and that you restarted the Go server, which does not reload itself.
Response to preflight request doesn't pass access control check
The OPTIONS request got an answer the browser did not accept. Usually your router returned 404 or 405 because only POST is registered for that path, so the middleware never ran. Handle OPTIONS in middleware and abort there, as above.
$curl -i -X OPTIONS http://localhost:8080/api/users \-H "Origin: http://localhost:3000" \-H "Access-Control-Request-Method: POST"# want: 204, with Access-Control-Allow-Origin echoing your origin
The value of the 'Access-Control-Allow-Origin' header must not be the wildcard '*' when the request's credentials mode is 'include'
Exactly what it says, and the fix is to echo the caller's origin rather than send a wildcard. This is the error that tells you your wildcard CORS was always going to break the day you added login.
Request header field authorization is not allowed by Access-Control-Allow-Headers
The preflight listed a header your allow-list does not name. Add it. The list is literal: a header you forgot is a request the browser refuses to send, and it names the missing one for you.
The login returns 200 and the next request is still unauthenticated
Work through it in this order, because each step makes the next observable.
- Devtools, Network, the login response. Is there a
Set-Cookieheader at all? If not, the server never set it. - Devtools, Application, Cookies. Is the cookie stored? If the response had it and the browser did not keep it, the attributes are wrong:
SameSite=NonewithoutSecureis dropped in silence. - The next request, Request Headers. Is the cookie sent? If it is stored and not sent, it is
SameSite, or aPathnarrower than the path you are calling. - Is
credentials: 'include'on that particular call? One forgottenfetchis enough.
It works on localhost and fails in production
The usual cause is SameSite=Lax. Your two development ports are the same site, so Lax is fine there, and your production frontend and API are on different domains, where it is not. The same mechanism also explains the reverse: a config built for production, with SameSite=None; Secure, drops the cookie on plain-HTTP localhost.
How a generated project does it
A Grit project ships this configured. The API reads its allowed origins from CORS_ORIGINS, the client sets credentials: 'include' in one place, the refresh cookie is HttpOnly and scoped to /api/auth, and the access token is held in memory rather than in localStorage, where any script on the page can read it.
The scoped Path is worth copying even if you take nothing else: a refresh token that is only sent to the endpoints that refresh it is not exposed on the other several hundred requests your app makes.
The auth reference has the whole scheme, including rotation and replay detection.
Frequently asked questions
- Why does it work in Postman but not in the browser?
- Because CORS is a browser rule and nothing else implements it. Postman, curl, your Go tests and a native mobile app all ignore it entirely. A tool that bypasses the rule cannot tell you whether you have satisfied it, which is why "it works in Postman" is not evidence of anything here.
- Should I store the JWT in localStorage?
- No. Any script running on your page can read
localStorage, including one that arrived through a compromised dependency, so a single cross-site scripting hole becomes every user's token. Keep the refresh token in anHttpOnlycookie, which JavaScript cannot read, and hold the short-lived access token in memory. - Is a wildcard CORS origin ever acceptable?
- Only for an API that is genuinely public and takes no credentials: a read-only endpoint serving data anyone may have. The moment a cookie or an Authorization header is involved, the browser refuses the wildcard anyway, so the choice is made for you.
- Should I proxy through Next.js or call the Go API directly?
- Proxy if the web app is your only client: it removes CORS, cookies become first-party, and there is less to get wrong. Call directly if you will also have a mobile app, a desktop app or third-party consumers, because those cannot use the proxy and the direct path has to be correct regardless.
- Why can my server component reach the API when my browser code cannot?
- Because the server component runs on the server, where CORS does not exist. That asymmetry is a useful diagnostic: if the server fetch works and the client fetch does not, the problem is CORS and not your API. Note that the two may also need different URLs, since inside Docker the server reaches the API by service name.
Next steps
- Build your first full-stack appWhere this problem first appears, with the smallest fix that gets you moving.
- Fix the errors you hit starting outThe exact messages, with the cause and the fix per operating system.
- Authentication referenceSessions, refresh rotation and replay detection as a generated project does them.
- Fetching data in the frontendThe generated client and hooks, where credentials and the base URL are decided.
