Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Session is missing when using getAccessToken from Route Handlers #1860

Closed
6 tasks done
brndt opened this issue Dec 31, 2024 · 2 comments
Closed
6 tasks done

Session is missing when using getAccessToken from Route Handlers #1860

brndt opened this issue Dec 31, 2024 · 2 comments

Comments

@brndt
Copy link

brndt commented Dec 31, 2024

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:

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).*)'
  ]
}

route handler:

export async function GET(request: Request, props: { params: Promise<{ email: string }> }) {
  const { email } = await props.params

  // session is always missing here 
  const { token } = await auth0.getAccessToken()
    
  const resp = await fetch(apiConfig.mainUrl + `my-profile/` + email, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${token}`
    },
    next: { revalidate: 300 }
  })

  return NextResponse.json(await resp.json())
}

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

@andresmarpz
Copy link

Maybe 4.0.0-beta.14 at #1858 fixes it. Seems to be related to issue #1841.

@guabu
Copy link
Contributor

guabu commented Jan 3, 2025

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.

@brndt brndt closed this as completed Jan 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants