Quick Start
UseverifyNextAuth to authenticate Next.js App Router API routes and middleware. It handles both cookies and Authorization headers.
Function Signature
Parameters
The Next.js request object from your API route or middleware
Configuration options for authentication
Return Value
Whether authentication was successful
User authentication context (always present when
success: true, optional with guest mode)Error message when
success: falseUsage Examples
API Route (App Router)
POST Route with Data
Route with Required Scope
Next.js Middleware
Protect multiple routes with Next.js middleware:Guest Mode
Allow both authenticated and guest users:Reusable Auth Helper
Create a helper function for consistent authentication:Server Actions (Experimental)
For Next.js Server Actions, extract the token from cookies:For Server Actions, use the generic
verifyAuth function instead of verifyNextAuth. See Generic Usage for details.Error Handling
With allowGuest: false (default)
With allowGuest: true
Common Error Messages
No token found in cookies or Authorization header
No token found in cookies or Authorization header
Token verification failed: Token has expired
Token verification failed: Token has expired
The JWT token’s expiration time has passed.Solution: Refresh the token on the frontend or prompt user to re-authenticate.
Invalid issuer
Invalid issuer
Token wasn’t issued by your Logto server.Solution: Verify
logtoUrl matches your Logto tenant URL.Invalid audience
Invalid audience
Token’s audience claim doesn’t match your API resource.Solution: Verify
audience matches the API resource registered in Logto.Missing required scope
Missing required scope
Token doesn’t include the required scope.Solution: Ensure the scope is requested during frontend authentication.
Best Practices
Return Appropriate Status Codes
401 Unauthorized: Authentication failed or missing403 Forbidden: Authenticated but insufficient permissions
Related
Express Middleware
Middleware for Express.js applications
Generic Usage
Flexible verifyAuth for any environment