Hi,
I’m trying to run the ‘call your APIs on user’s behalf’ Auth for GenAI tutorial and get stuck with the following error:
Error: cookies was called outside a request scope. Read more:
src/middleware.ts (13:31) @ middleware
11 |
12 | const { origin } = new URL(request.url);
13 | const session = await auth0.getSession();
| ^
14 |
15 | // User does not have a session — redirect to login.
16 | if (!session) {
Has the been seen elsewhere?
Hi @rustopher
Welcome to the Auth0 Community!
Thank you for posting your error. Can you check for me which Next.js version you are running? I’ve checked internally that this issue occurred on the Next.js v4.4.1. Alternatively, can you try to clone the working sample directly from the repository-> auth0-ai-samples/call-apis-on-users-behalf/your-api-next-js at main · auth0-samples/auth0-ai-samples · GitHub
Thanks
Dawid
1 Like
Thanks @dawid.matuszczyk,
I’m running @auth0/nextjs-auth0@4.8.0 and next@15.3.5. I’ve tried cloning the working sample and get the same error, which makes it sound environmental (MBPro, M4 Max chip).
Hi @rustopher
I am sorry about the delayed response to the issue that you were facing at the time.
Does this still persists by any chance?
I believe that the cause might be caused by you are calling await auth0.getSession() inside your middleware without passing the request object to it. You middleware.ts code should look something like this:
// src/middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { auth0 } from './lib/auth0';
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
const session = await auth0.getSession(request, response);
if (!session) {
return NextResponse.redirect(new URL('/api/auth/login', request.url));
}
response.headers.set('x-user-id', session.user.sub);
return response;
}
Hopefully, this will be useful for anybody else who stumbled upon the same issue. If you have found a different fix, please feel free to share it with the rest of us!
Kind Regards,
Nik