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
Options Details
Options Details
refresh: Force token refresh even if not expiredaudience: Request token for specific API audiencescope: Request specific scopes (for MRRT)
Returns
Returns aPromise 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:Token Refresh Buffer
Refresh tokens proactively before expiration:lib/auth0.ts
Race Condition Mitigation
Check token expiry before critical operations:Error Handling
The method throwsAccessTokenError 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.
Refresh Token Rotation
Important Notes
The response includes:
token: The access token stringexpiresAt: Token expiration as seconds since Unix epochscope: 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:Related Methods
getSession
Get full session data
updateSession
Update session data