Skip to main content
Protect your API routes to ensure only authenticated users can access them. The SDK provides the withApiAuthRequired helper for both App Router and Pages Router.

App Router

Protect App Router route handlers by wrapping them with withApiAuthRequired.
1

Create your route handler

Create a route handler file in your app directory:
app/api/protected/route.ts
2

Test the route

Test your protected route by making a request:
Without authentication, you’ll receive a 401 Unauthorized response.

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 with withApiAuthRequired.
1

Create your API route

Create an API route file in your pages/api directory:
pages/api/protected.ts
2

Test the route

Make a request to test your protected route:
Without a valid session cookie, you’ll receive a 401 Unauthorized response.

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.
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 a 401 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, use getAccessToken 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:
  1. Check session cookie: Ensure the session cookie is being sent with requests
  2. Verify domain: If using subdomains, ensure cookie domain is set correctly
  3. Check SameSite: Set sameSite: "lax" for cross-origin requests

Session not available in App Router

If getSession() returns null in App Router:
  • Ensure you’re passing the req parameter: auth0.getSession(req)
  • Verify middleware is running on the request path
  • Check that cookies are being sent from the client

CORS Issues

For API routes called from different origins: