Protect your Next.js pages to ensure only authenticated users can access them. The SDK provides theDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/auth0/nextjs-auth0/llms.txt
Use this file to discover all available pages before exploring further.
withPageAuthRequired helper for both server-side and client-side page protection.
Server-Side Protection
Protect pages on the server to redirect unauthenticated users to login before they can access the page content.App Router
Wrap your Server Component withwithPageAuthRequired and provide a returnTo path since Server Components aren’t aware of the page’s URL.
The
returnTo option is required for App Router pages because Server Components don’t have access to the request URL. This ensures users are redirected back to the correct page after logging in.Dynamic Routes
For pages with dynamic route parameters, you can use a function forreturnTo to preserve the route:
app/posts/[slug]/page.tsx
Pages Router
UsewithPageAuthRequired to wrap your getServerSideProps function.
The SDK automatically adds the
user object to your page props.
Custom getServerSideProps
You can pass your owngetServerSideProps function, and the SDK will merge your props with the user:
pages/dashboard.tsx
Custom Return URL
Specify a customreturnTo URL for the login redirect:
pages/protected.tsx
Client-Side Protection
Protect client-rendered pages to redirect users on the client side. This is useful for pages that don’t need SEO or where you want client-side rendering.With Loading State
ThewithPageAuthRequired HOC passes a user prop and handles loading states automatically:
Comparison: Server vs Client
| Feature | Server-Side | Client-Side |
|---|---|---|
| SEO | ✅ Crawlable | ❌ Not crawlable |
| Initial Load | Protected from start | Brief flash possible |
| Use Case | Public-facing pages | Admin dashboards |
| Router | App Router, Pages Router | App Router only |
| Performance | Faster initial load | Slower (JS required) |
Best Practices
- Use server-side protection for pages that need SEO or contain sensitive data
- Use client-side protection for internal dashboards or admin panels
- Always specify
returnToin App Router to ensure users return to the correct page after login - Keep
returnToURLs registered in your Auth0 Dashboard under Allowed Callback URLs
Troubleshooting
Users not redirected after login
Ensure thereturnTo URL is registered in your Auth0 Application settings:
- Go to the Auth0 Dashboard
- Navigate to Applications > Your Application
- Add your URL to Allowed Callback URLs
Server Component errors
If you see “Server Component” errors with App Router:- Ensure you’re providing the
returnTooption - Don’t use
redirect()manually; letwithPageAuthRequiredhandle it
Pages Router props not merged
If custom props aren’t showing up:- Make sure your
getServerSidePropsreturns apropsobject - Don’t return
redirectornotFoundfrom your custom function; return props only