I’m running Next.js v14.2 and next-auth v4.24.
I am using middleware to intercept requests that go through my Next.js server and adding the Authorization
header if they have a server session.
This is what the code looks like:
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
const requestHeaders = new Headers(request.headers);
if (token?.access_token) {
requestHeaders.set("Authorization", `Bearer ${token.access_token}`);
}
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}
However, I am encountering a problem where the user keeps the tab on idle for some time, then sends a request when the JWT has expired. Thus, the server receiving this forwarded request returns a 401.
I am aware getServerSession
will automatically refresh the token, but when I tried implementing I got an error.
Here is the code:
export async function middleware(request: NextRequest) {
const token = await getServerSession(authOptions);
const requestHeaders = new Headers(request.headers);
if (token?.access_token) {
requestHeaders.set("Authorization", `Bearer ${token.access_token}`);
}
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}
Here’s the error:
Error [TypeError]: Cannot read properties of undefined (reading 'substring')
How should I go about solving this?