Dammy0.0.6413426
I have a Next.js 14 app router API route protected by JWT. The token is generated correctly on login, stored in localStorage, and attached to every request via an Authorization: Bearer <token> header.
But the API route keeps returning 401 Unauthorized even when I log the incoming headers — the authorization header is undefined.
Here is my fetch call:
const res = await fetch('/api/protected', { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, });
And here is my route handler:
export async function GET(request: Request) { const auth = request.headers.get('authorization'); console.log('auth header:', auth); // logs: null if (!auth) return new Response('Unauthorized', { status: 401 }); // ... }
I have verified the token exists in localStorage before the fetch runs. What am I missing?
Constank K0.0.4612577
The issue is almost certainly a CORS preflight stripping your custom headers.
When you add a non-standard header like Authorization to a cross-origin…
Connect your wallet to post a contribution.
Authorization, from cross-origin fetch requests.OPTIONS request before sending the actual request when a non-standard header is added to a cross-origin fetch.OPTIONS request must be handled properly to include the necessary headers and avoid stripping the custom headers.The core lesson is that CORS preflight requests can strip custom headers, such as Authorization, if not properly handled by the server.