Skip to main content

How to Forward the Authorization Header from a Next.js Route Handler

· 17 min read
Jagdish Kumawat
Founder @ Dewiride

When a page calls your Next.js route handler and the route calls an API for the signed-in user, the user's access token has to travel on: the browser sends it in an Authorization: Bearer header, and the route passes it to the API. Forwarding is one line, but which line matters. This guide forwards that header alone, refuses requests that don't have one, and turns the API's 401 and 403 into answers the page can act on.

How a Token Travels Through a Route​

An access token is a short piece of text that a sign-in service issues and an API checks. The browser sends it with each request in the Authorization header, after the word Bearer:

The header the browser sends
Authorization: Bearer <the access token>

The name says how it works. The OAuth 2.0 standard for these tokens, RFC 6750, defines a bearer token as a security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Whoever holds it is the user, as far as the API can tell. So a route that forwards it takes on the standard's first recommendation: Client implementations MUST ensure that bearer tokens are not leaked to unintended parties. In practice, the token goes to the API it was issued for and nowhere else: not into logs, and not into responses.

The route is the middle of three steps:

StepWhoWhat happens
1Browser → routeThe page calls the route with Authorization: Bearer …
2Route → APIThe route checks there is a token and passes that one header on
3API → route → browserThe API checks the token and answers; the route passes the answer, or a clear error, back

Step 1: A Stand-In for Your API​

A real API checks the token's digital signature, its expiry and who it was issued for. To keep the example about the route alone, the API here is a stand-in: a second route in the same app that knows two made-up tokens. Create app/api/upstream/route.ts:

app/api/upstream/route.ts
// Stands in for the API your route calls. A real API checks the access
// token's signature and contents; this one knows two made-up tokens, so the
// example runs without a sign-in.
const users = new Map([
["token-for-ana", { name: "Ana", allowed: true }],
["token-for-ben", { name: "Ben", allowed: false }],
]);

export async function GET(request: Request) {
const token = request.headers.get("authorization")?.replace(/^Bearer /, "");
const user = token ? users.get(token) : undefined;
if (!user) {
return Response.json(
{ error: "The access token is missing or not valid." },
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
);
}
if (!user.allowed) {
return Response.json(
{ error: "The access token doesn't allow this." },
{ status: 403 },
);
}
return Response.json({
message: `Hello, ${user.name}.`,
// The names of the headers that arrived, never their values.
headersReceived: [...request.headers.keys()],
});
}

It answers the way a real API does:

TokenAnswer
Missing or unknown401 Unauthorized: the token isn't valid
token-for-ben403 Forbidden: the token is valid but doesn't allow this
token-for-ana200 OK with a greeting and the names of the headers it received, so you can see what the route forwarded without any value appearing

The Microsoft Agent Framework series builds a real one: an ASP.NET Core API that accepts only Microsoft Entra ID access tokens issued for it.

Step 2: Refuse Requests Without a Bearer Token​

The route the browser calls is app/api/hello/route.ts. It starts by reading the header:

app/api/hello/route.ts (the start of GET)
export async function GET(request: Request) {
// Only requests that carry a bearer token go on to the API.
const authorization = request.headers.get("authorization");
if (!authorization?.startsWith("Bearer ")) {
return Response.json(
{ error: "Sign in first." },
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
);
}
CodeWhat it does
request.headers.get("authorization")Reads the header. Header names aren't case-sensitive, so Authorization arrives here too. Without the header, the result is null
?.startsWith("Bearer ")true only for a header that starts with Bearer and a space
status: 401Unauthorized: the request has no valid credentials
"WWW-Authenticate": "Bearer"Says which kind of credentials the route expects

A request without a token never reaches the API: the route answers it alone. The WWW-Authenticate header belongs with every 401. MDN's page on 401 Unauthorized says the status is sent with an HTTP WWW-Authenticate response header that contains information on the authentication scheme the server expects.

The route doesn't try to tell a good token from a bad one. That is the API's job, and the API has to check every token it receives anyway.

Step 3: Forward Only the Authorization Header​

Next, the call to the API, with a headers object built from scratch:

app/api/hello/route.ts (the call to the API)
// Pass on the Authorization header, and nothing else from the browser.
const upstream = await fetch(new URL("/api/upstream", request.url), {
headers: { Authorization: authorization },
signal: request.signal,
});
CodeWhat it does
new URL("/api/upstream", request.url)The stand-in's address, built from the request's own. In your app, this is your API's address, usually from a setting
headers: { Authorization: authorization }The one header the API needs, exactly as the browser sent it
signal: request.signalEnds the call to the API when the browser leaves (How to Cancel an Upstream Request When the Browser Disconnects in Next.js)

The browser sends much more than a token: cookies, its language, details about itself. None of it is meant for the API. The section after Step 5 shows what happens when it all goes along.

Step 4: Pass the API's 401 and 403 On​

The API's answer comes back to the route, and its status says what the page should do next. RFC 6750 gives the two that matter here their meaning. A 401 is for a token that is expired, revoked, malformed, or invalid for other reasons, and the standard adds: The client MAY request a new access token and retry the protected resource request. A 403 is for a request that requires higher privileges than provided by the access token:

app/api/hello/route.ts (the API's answer)
// The API refused the token: tell the browser what to do next.
if (upstream.status === 401) {
return Response.json(
{ error: "Your sign-in isn't valid anymore. Sign in again." },
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
);
}
if (upstream.status === 403) {
return Response.json(
{ error: "You don't have access to this." },
{ status: 403 },
);
}
if (!upstream.ok) {
console.error(`The API answered ${upstream.status}.`);
return Response.json(
{ error: "The service isn't available right now." },
{ status: 502 },
);
}

return Response.json(await upstream.json());
}
The API answersThe route answersSo the page can
401401 and Sign in againGet a new token, or sign the person in again
403403 and You don't have access to thisTell the person, instead of retrying
Any other failure502 Bad Gateway, and a log line with the status onlyShow that the service is down
SuccessThe API's JSONUse it

The log line names the status and nothing else. The token never appears in a log or in a response.

The complete route:

app/api/hello/route.ts
export async function GET(request: Request) {
// Only requests that carry a bearer token go on to the API.
const authorization = request.headers.get("authorization");
if (!authorization?.startsWith("Bearer ")) {
return Response.json(
{ error: "Sign in first." },
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
);
}

// Pass on the Authorization header, and nothing else from the browser.
const upstream = await fetch(new URL("/api/upstream", request.url), {
headers: { Authorization: authorization },
signal: request.signal,
});

// The API refused the token: tell the browser what to do next.
if (upstream.status === 401) {
return Response.json(
{ error: "Your sign-in isn't valid anymore. Sign in again." },
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
);
}
if (upstream.status === 403) {
return Response.json(
{ error: "You don't have access to this." },
{ status: 403 },
);
}
if (!upstream.ok) {
console.error(`The API answered ${upstream.status}.`);
return Response.json(
{ error: "The service isn't available right now." },
{ status: 502 },
);
}

return Response.json(await upstream.json());
}

macOS-style code window titled app/api/hello/route.ts showing a GET route handler that answers 401 when there is no Bearer token, calls the API with only the Authorization header and the request's signal, maps the API's 401 and 403 to its own messages, answers 502 for other failures and returns the API's JSON

Step 5: Try It​

Start the development server. -p 3011 serves the app on port 3011, because another app on my computer uses the default port, 3000:

Terminal
npx next dev -p 3011

In a second terminal, call the route without a token. curl comes with macOS, Windows 10 and later, and most Linux distributions; -i prints the status and headers before the body:

Terminal
curl -i http://localhost:3011/api/hello

In PowerShell, type curl.exe: in Windows PowerShell, curl on its own runs a different command.

Response
HTTP/1.1 401 Unauthorized
content-type: application/json
www-authenticate: Bearer

{"error":"Sign in first."}

Here and below I left out the general headers, such as Date and Connection. Now Ana's token, together with a cookie, the way a browser sends one for a site that keeps a session. -H adds a header and -b a cookie:

Terminal
curl -i http://localhost:3011/api/hello -H 'Authorization: Bearer token-for-ana' -b 'session=abc123'
Response
HTTP/1.1 200 OK
content-type: application/json

{"message":"Hello, Ana.","headersReceived":["accept","accept-encoding","accept-language","authorization","connection","host","sec-fetch-mode","user-agent","x-forwarded-for","x-forwarded-host","x-forwarded-port","x-forwarded-proto"]}

The API received authorization, and no cookie. The other names aren't from the browser either:

Header namesWhere they come from
accept, accept-encoding, accept-language, connection, host, sec-fetch-mode, user-agentNode.js's fetch adds them to every request it sends
x-forwarded-for, x-forwarded-host, x-forwarded-port, x-forwarded-protoNext.js adds them to the requests it receives, and the stand-in API runs in the same Next.js app. A request sent straight to /api/upstream with curl arrives with them too

Then Ben's token, which the API knows but doesn't allow, and a token it doesn't know:

Terminal
curl -i http://localhost:3011/api/hello -H 'Authorization: Bearer token-for-ben'
curl -i http://localhost:3011/api/hello -H 'Authorization: Bearer old-token'
Response (token-for-ben)
HTTP/1.1 403 Forbidden
content-type: application/json

{"error":"You don't have access to this."}
Response (old-token)
HTTP/1.1 401 Unauthorized
content-type: application/json
www-authenticate: Bearer

{"error":"Your sign-in isn't valid anymore. Sign in again."}

The development server's terminal logged every request, the route's calls to the stand-in API included:

Output (the development server's terminal)
GET /api/hello 401 in 37ms (next.js: 27ms, application-code: 10ms)
GET /api/upstream 200 in 14ms (next.js: 7ms, application-code: 7ms)
GET /api/hello 200 in 72ms (next.js: 1.9ms, application-code: 70ms)
GET /api/hello 403 in 7ms (next.js: 0.5ms, application-code: 7ms)
GET /api/upstream 403 in 4ms (next.js: 0.6ms, application-code: 3ms)
GET /api/hello 401 in 6ms (next.js: 0.6ms, application-code: 6ms)
GET /api/upstream 401 in 4ms (next.js: 0.4ms, application-code: 3ms)

The first request, the one without a token, has no /api/upstream line: the route answered it alone. Each of the other three reached the API once, and the API's 403 and 401 reached curl as the route's own messages, with the same status codes.

Why Not Forward Every Header?​

Passing request.headers straight to fetch also works, and it is shorter. To see what it sends, add a second route that does exactly that, app/api/hello-all-headers/route.ts:

app/api/hello-all-headers/route.ts
// Don't do this: it passes every header from the browser, cookies
// included, on to the API.
export async function GET(request: Request) {
const upstream = await fetch(new URL("/api/upstream", request.url), {
headers: request.headers,
signal: request.signal,
});
return Response.json(await upstream.json(), { status: upstream.status });
}

Call both routes with the same token and cookie. Without -i, curl prints only the response body, and -s (silent) turns off its progress and error messages:

Terminal
curl -s http://localhost:3011/api/hello -H 'Authorization: Bearer token-for-ana' -b 'session=abc123'
curl -s http://localhost:3011/api/hello-all-headers -H 'Authorization: Bearer token-for-ana' -b 'session=abc123'

macOS-style terminal window with two curl calls carrying the same bearer token and session cookie: the response of /api/hello lists the headers the API received without a cookie, and the response of /api/hello-all-headers lists the same headers plus cookie

Output
{"message":"Hello, Ana.","headersReceived":["accept","accept-encoding","accept-language","authorization","connection","host","sec-fetch-mode","user-agent","x-forwarded-for","x-forwarded-host","x-forwarded-port","x-forwarded-proto"]}
{"message":"Hello, Ana.","headersReceived":["accept","accept-encoding","accept-language","authorization","connection","cookie","host","sec-fetch-mode","user-agent","x-forwarded-for","x-forwarded-host","x-forwarded-port","x-forwarded-proto"]}

The second list has cookie. With request.headers, the browser's cookie for your site went to the API, which has no use for it and now holds it. curl sent only a few headers; a real browser sends many more, and request.headers passes them on as well. Building the headers object yourself means the API gets what you chose, and only that.

Common Mistakes​

MistakeWhat happensDo this instead
headers: request.headersCookies and every other browser header reach the APIheaders: { Authorization: authorization }
Logging the Authorization headerAnyone who can read the logs can use the token as that personLog the status, never the token
Calling the API when there is no tokenOne pointless call for every request that isn't signed inAnswer 401 in the route first
Turning the API's 401 or 403 into 500The page can't tell sign in again from something brokePass 401 and 403 on, with messages
A 401 without WWW-AuthenticateThe client isn't told which credentials to send; RFC 6750 says the API MUST include itAdd "WWW-Authenticate": "Bearer"

Troubleshooting​

SymptomLikely causeFix
Every request gets 401 Sign in first.The request has no Authorization header, or it doesn't start with Bearer and a spaceSend Authorization: Bearer followed by the token
401 Your sign-in isn't valid anymoreThe API refused the token: expired, revoked or not meant for itGet a new token and send the request again
403 You don't have access to thisThe token is valid, but doesn't allow this requestAsk for the permission the API requires when you get the token
502 and The API answered 500. in the logThe API failedLook at the API's own logs

FAQ​

Should the route check the token itself?​

Only that there is one. Whether a token is genuine, unexpired and meant for this API is the API's decision, and the API has to make it for every request it receives. Checking it in the route as well would mean keeping the same settings in two places.

Where does the browser get the token?​

From the sign-in. In a React app signed in with Microsoft Entra ID, MSAL React asks for the token just before each call: How to Get an Access Token with MSAL React.

Does this work for POST requests?​

The pattern is the same for every method: read the header, check it, and put it in the headers of your fetch. The Microsoft Agent Framework series does it in a POST route that streams an AI agent's answer, and turns the API's 401 and 403 into a message in the chat.

Conclusion​

A route handler that calls an API for the user reads the Authorization header, answers 401 with WWW-Authenticate: Bearer when there is no bearer token, and sends the API that one header in a headers object it builds itself. When the API answers 401 or 403, the route passes the status on with a message the page can act on, and the token never shows up in a log or a response.

Additional Resources​