Skip to main content
The getAccessToken method retrieves the access token for the currently authenticated user, automatically refreshing it if expired and a refresh token is available.

Method Signatures

Parameters

IncomingMessage | NextApiRequest | NextRequest
The request object (Pages Router and middleware only)
ServerResponse | NextApiResponse | NextResponse
The response object (Pages Router and middleware only)
GetAccessTokenOptions
Optional configuration for token retrieval
  • refresh: Force token refresh even if not expired
  • audience: Request token for specific API audience
  • scope: Request specific scopes (for MRRT)

Returns

Returns a Promise that resolves to:

Usage Examples

App Router

Pages Router

Middleware

middleware.ts

Advanced Usage

Force Token Refresh

Force a token refresh even if not expired:
This is useful when user permissions or scopes have changed and you need to ensure the token reflects the latest state.

Multi-Resource Refresh Tokens (MRRT)

Request tokens for different audiences:
When using MRRT, ensure your Auth0 Application’s Refresh Token Policies are configured with the required audiences.

Token Refresh Buffer

Refresh tokens proactively before expiration:
lib/auth0.ts

Race Condition Mitigation

Check token expiry before critical operations:

Error Handling

The method throws AccessTokenError when:
  • User has no active session
  • Token refresh fails
  • MFA is required (throws MfaRequiredError)

Session Persistence

When tokens are refreshed, the updated token set is automatically persisted to the session.
Server Components cannot set cookies. Calling getAccessToken() in a Server Component will refresh the token if expired, but the updated token set will not be persisted.To ensure token updates are saved, call getAccessToken(req, res) in middleware or API routes.

Refresh Token Rotation

If your Auth0 application uses Refresh Token Rotation, configure an overlap period in the Auth0 Dashboard to prevent race conditions when multiple requests attempt to refresh tokens simultaneously.Navigate to: Applications > Advanced Settings > OAuth

Important Notes

The response includes:
  • token: The access token string
  • expiresAt: Token expiration as seconds since Unix epoch
  • scope: Granted scopes (if available)
  • token_type: Usually “Bearer”
  • audience: Token audience (if specified)
For Pages Router middleware, pass both request and response objects to ensure refreshed tokens can be read in the same request:

getSession

Get full session data

updateSession

Update session data