Skip to main content

Quick Start

Use verifyNextAuth to authenticate Next.js App Router API routes and middleware. It handles both cookies and Authorization headers.

Function Signature

Parameters

request
NextRequest
required
The Next.js request object from your API route or middleware
options
VerifyAuthOptions
required
Configuration options for authentication

Return Value

success
boolean
required
Whether authentication was successful
auth
AuthContext
User authentication context (always present when success: true, optional with guest mode)
error
string
Error message when success: false

Usage 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 authentication token was provided in the request.Solution: Ensure the frontend is setting cookies or sending Authorization header.
The JWT token’s expiration time has passed.Solution: Refresh the token on the frontend or prompt user to re-authenticate.
Token wasn’t issued by your Logto server.Solution: Verify logtoUrl matches your Logto tenant URL.
Token’s audience claim doesn’t match your API resource.Solution: Verify audience matches the API resource registered in Logto.
Token doesn’t include the required scope.Solution: Ensure the scope is requested during frontend authentication.

Best Practices

1

Use Environment Variables

Store Logto configuration in environment variables:
2

Create Helper Functions

Wrap verifyNextAuth in helper functions for consistent error handling:
3

Return Appropriate Status Codes

  • 401 Unauthorized: Authentication failed or missing
  • 403 Forbidden: Authenticated but insufficient permissions
4

Validate Auth Context

Always check isAuthenticated when using guest mode:

Express Middleware

Middleware for Express.js applications

Generic Usage

Flexible verifyAuth for any environment