I am using the App Router. This code works when placed inside the component folder as app/trials/route.ts
but gives 401 unauthorized
when used as a route handler at app/api/trials/route.ts
import { NextResponse } from 'next/server';
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
export const GET = withApiAuthRequired(async function trials(req:any, res:any) {
const { accessToken } = await getAccessToken(req, res);
const config = { headers: { Authorization: `Bearer ${accessToken}` }};
const response = await fetch('https://myexternalapi.io/api/trials', config);
const trials = await response.json();
return NextResponse.json({ trials })
});
In the server logs…
GET /trials 200 in 317ms
GET /api/auth/me 200 in 9ms
GET /api/auth/me 200 in 5ms
GET /api/trials 401 in 5ms
Response {
[Symbol(realm)]: null,
[Symbol(state)]: {
aborted: false,
rangeRequested: false,
timingAllowPassed: true,
requestIncludesCredentials: true,
type: 'default',
status: 401,
timingInfo: {
startTime: 27883.867709,
redirectStartTime: 0,
redirectEndTime: 0,
postRedirectStartTime: 27883.867709,
finalServiceWorkerStartTime: 0,
finalNetworkResponseStartTime: 0,
finalNetworkRequestStartTime: 0,
endTime: 0,
encodedBodySize: 110,
decodedBodySize: 110,
finalConnectionTimingInfo: null
},
cacheState: '',
statusText: 'Unauthorized',
headersList: HeadersList {
cookies: null,
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: null
},
urlList: [ URL {} ],
body: { stream: undefined }
},
[Symbol(headers)]: HeadersList {
cookies: null,
[Symbol(headers map)]: Map(6) {
'vary' => [Object],
'content-type' => [Object],
'date' => [Object],
'connection' => [Object],
'keep-alive' => [Object],
'transfer-encoding' => [Object]
},
[Symbol(headers map sorted)]: null
}
}
GET /trials 200 in 136ms
GET /api/auth/me 200 in 6ms
GET /api/auth/me 200 in 4ms
There just isn’t any good documentation on doing this with the App Router and with the nextjs-auth0 library. Any guess what I’m doing wrong? I was expecting to be able to attach the token and keep everything server rendered. Thanks!