withApiAuthRequired helper for both App Router and Pages Router.
App Router
Protect App Router route handlers by wrapping them withwithApiAuthRequired.
Create your route handler
Create a route handler file in your
app directory:app/api/protected/route.ts
Multiple HTTP Methods
Protect multiple HTTP methods in the same route file:app/api/data/route.ts
Dynamic Routes
Access route parameters in protected API routes:app/api/posts/[id]/route.ts
Pages Router
Protect Pages Router API routes by wrapping the handler function withwithApiAuthRequired.
Handling Different HTTP Methods
Handle multiple HTTP methods in a single Pages Router API route:pages/api/data.ts
Dynamic API Routes
Access dynamic route parameters in Pages Router:pages/api/posts/[id].ts
Calling Protected API Routes
Once your API routes are protected, you can call them from your frontend with the session cookie.- App Router
- Pages Router
Call protected API routes from client components:
app/products/page.tsx
Error Responses
When a request to a protected API route fails authentication, the SDK returns a401 Unauthorized response:
Accessing User Information
Access the authenticated user’s information within your protected API route:Calling External APIs
To call external APIs from your protected routes, usegetAccessToken to obtain an access token:
app/api/external-data/route.ts
Learn more about obtaining and using access tokens in the Access Tokens guide.
Best Practices
- Always validate user permissions beyond just authentication when accessing sensitive resources
- Use TypeScript for type safety with request/response objects
- Handle errors gracefully and return appropriate HTTP status codes
- Never expose sensitive data in error messages
- Use HTTPS in production to protect session cookies from interception
Troubleshooting
401 Errors with Valid Session
If you’re getting 401 errors despite being logged in:- Check session cookie: Ensure the session cookie is being sent with requests
- Verify domain: If using subdomains, ensure cookie domain is set correctly
- Check SameSite: Set
sameSite: "lax"for cross-origin requests
Session not available in App Router
IfgetSession() returns null in App Router:
- Ensure you’re passing the
reqparameter:auth0.getSession(req) - Verify middleware is running on the request path
- Check that cookies are being sent from the client