Need help with Next.js App Router + Auth0 v4 Session Issues during SSR
Unanswered
Chippiparai posted this in #help-forum
ChippiparaiOP
I'm having issues with session handling in my Next.js 14 app using the new Auth0 v4 SDK. The app uses App Router with both Server and Client Components, and has a Python backend where calls to
## Setup
- Using
- Tanstack Query for data fetching
- Mix of Server and Client Components
## The Issue
The middleware correctly checks the session for page routes, but during server-side rendering, API requests made by Server Components are failing with 401s even though the page itself has a valid session (The calls to
Here's the relevant middleware code:
And a simplified API route:
## The Behavior
1. User requests
2. Middleware checks session -> succeeds
3. During SSR, the page makes 3 API requests
4. These API requests fail with 401 (no session)
5. After hydration, client-side requests work fine
/api/*
routes are passed through.## Setup
- Using
@auth0/nextjs-auth0
v4 for auth- Tanstack Query for data fetching
- Mix of Server and Client Components
## The Issue
The middleware correctly checks the session for page routes, but during server-side rendering, API requests made by Server Components are failing with 401s even though the page itself has a valid session (The calls to
/api
routes from the server components have a null session)Here's the relevant middleware code:
export async function middleware(request: NextRequest) {
const authRes = await auth0.middleware(request);
if (request.nextUrl.pathname.startsWith("/auth/")) {
return authRes;
}
const session = await auth0.getSession();
if (request.nextUrl.pathname.startsWith("/api/")) {
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
}
if (!session) {
const { origin } = new URL(request.url);
return NextResponse.redirect(
`${origin}/auth/login?returnTo=${request.nextUrl.pathname}`,
);
}
return authRes;
}
And a simplified API route:
export async function GET(
request: NextRequest,
{ params }: { params: { path: string[] } },
) {
const { path } = params;
const session = await auth0.getSession();
const routePath = "/" + path.join("/");
return fetch(env.BACKEND_URL + routePath, {
headers: {
Authorization: `Bearer ${session?.tokenSet.accessToken}`,
credentials: "include",
},
});
}
## The Behavior
1. User requests
/pageRoute
2. Middleware checks session -> succeeds
3. During SSR, the page makes 3 API requests
4. These API requests fail with 401 (no session)
5. After hydration, client-side requests work fine
1 Reply
ChippiparaiOP
Going a different route with this I think using server actions instead of hitting API routes from within a server component. But for that im also hitting an issue callling those from server components with errors about using them during initial render.