You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hey @guabu!
I have a problem when calling route handler from middleware: I need to make an api call to my backend in order to retrieve user additional fields and check if they have admin role.
The problem is that even when I have a session in middleware, route handler somehow doesn't seem to find it.
middleware:
import { NextResponse, type NextRequest } from 'next/server'
import { auth0 } from './lib/auth0'
import { Nullable } from './lib/types'
import { UserPrivateView } from './models/user-private-view'
export async function middleware(request: NextRequest) {
const { origin } = new URL(request.url)
const authResponse = await auth0.middleware(request)
const session = await auth0.getSession()
if (request.nextUrl.pathname.startsWith('/api') || request.nextUrl.pathname.startsWith('/auth')) {
return authResponse
}
if (!session) {
return NextResponse.redirect(`${origin}/auth/login`)
}
// make an api call to my backend in order to retrieve additional fields
const userData = await fetch(`${origin}/api/my-profile/${session?.user.email}`)
const user: Nullable<UserPrivateView> = await userData.json()
if (!user) {
return NextResponse.redirect(`${origin}/unauthorized`)
}
return authResponse
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)'
]
}
Hey @brndt 👋 When calling the Server Route from a middleware, you are making a server-to-server request. In this case, the cookies will not be forwarded by the middleware to your Server Route which is why you're always seeing that there is no session. This is expected behavior.
If the middleware and Server Route are in the same code base, you should be able to avoid the network request and call the function directly.
Checklist
Description
Hey @guabu!
I have a problem when calling route handler from middleware: I need to make an api call to my backend in order to retrieve user additional fields and check if they have admin role.
The problem is that even when I have a session in middleware, route handler somehow doesn't seem to find it.
middleware:
route handler:
Am I missing something or is it a bug?
Reproduction
...
Additional context
No response
nextjs-auth0 version
4.0.0-beta.13
Next.js version
15.1.3
Node.js version
22.10.2
The text was updated successfully, but these errors were encountered: