
Auth0 Nextjs
Add Auth0 login, session handling, access tokens, and protected API routes to a Next.js app with copy-ready TypeScript patterns.
Overview
Auth0-nextjs is an agent skill for the Build phase that implements Auth0 login, sessions, and access-token API calls in Next.js apps.
Install
npx skills add https://github.com/auth0/agent-skills --skill auth0-nextjsWhat is this skill?
- Custom login links and programmatic `router.push` with `returnTo` destinations
- Server route pattern to obtain access tokens and call external APIs with Bearer auth
- Silent session behavior with refresh tokens plus `prompt=login` forced re-authentication
- Advanced `Auth0Client` setup with domain, client credentials, audience, and authorization parameters
- Environment-driven configuration for AUTH0_DOMAIN, secrets, and APP_BASE_URL
Adoption & trust: 1.3k installs on skills.sh; 26 GitHub stars; 2/3 security scanners passed (skills.sh audits).
What problem does it solve?
You are adding login to Next.js but struggle to wire return URLs, server-side tokens, and external API authorization correctly.
Who is it for?
Solo builders on the Auth0 Next.js SDK who need vetted snippets for login links, tokenized fetch, and Auth0Client config.
Skip if: Non-Next.js stacks, auth-free static sites, or teams that need full threat modeling and compliance review from this skill alone.
When should I use this skill?
User is implementing or debugging Auth0 authentication in a Next.js project including login routes, tokens, or Auth0Client configuration.
What do I get? / Deliverables
After applying the patterns, users can sign in via Auth0, stay signed in with refresh behavior, and your routes can fetch bearer tokens for backend APIs.
- Login and returnTo navigation patterns
- Protected API route using access token
- Auth0Client configuration module
Recommended Skills
Journey fit
Authentication and token plumbing are backend build work before you can ship a secure SaaS dashboard or API. Auth0 Next.js SDK patterns sit in server routes, middleware, and env-based client configuration—not marketing or ops tooling.
How it compares
Pattern library for Auth0’s official Next.js SDK—not a replacement for Auth0 tenant security settings or OWASP review.
Common Questions / FAQ
Who is auth0-nextjs for?
Indie developers and small teams building Next.js SaaS or APIs who want agent-guided Auth0 setup for login, sessions, and token-backed server routes.
When should I use auth0-nextjs?
During build when adding `/auth/login`, protecting dashboards with returnTo, calling external APIs with `getAccessToken`, or configuring Auth0Client env vars.
Is auth0-nextjs safe to install?
The skill references client secrets and tokens in env config—review the Security Audits panel on this Prism page and never commit secrets to the repo.
SKILL.md
READMESKILL.md - Auth0 Nextjs
## Common Patterns ### Custom Login with Options ```typescript <a href="/auth/login?returnTo=/dashboard"> Login and go to Dashboard </a> ``` Or programmatically: ```typescript const router = useRouter(); router.push('/auth/login?returnTo=/dashboard'); ``` --- ### Get Access Token for External APIs ```typescript import { auth0 } from '@/lib/auth0'; import { NextResponse } from 'next/server'; export async function GET() { const { token } = await auth0.getAccessToken(); if (!token) { return new NextResponse('Unauthorized', { status: 401 }); } const apiResponse = await fetch('https://external-api.com/data', { headers: { Authorization: `Bearer ${token}` } }); return NextResponse.json(await apiResponse.json()); } ``` --- ### Silent Authentication Users remain logged in across sessions automatically with refresh tokens. To force re-authentication: ```typescript <a href="/auth/login?prompt=login"> Force Re-login </a> ``` --- ## Configuration Options ### Advanced Auth0 Configuration Create `lib/auth0.ts`: ```typescript import { Auth0Client } from '@auth0/nextjs-auth0/server'; export const auth0 = new Auth0Client({ domain: process.env.AUTH0_DOMAIN!, clientId: process.env.AUTH0_CLIENT_ID!, clientSecret: process.env.AUTH0_CLIENT_SECRET!, secret: process.env.AUTH0_SECRET!, appBaseUrl: process.env.APP_BASE_URL!, authorizationParameters: { scope: 'openid profile email', audience: process.env.AUTH0_AUDIENCE, }, routes: { login: '/auth/login', callback: '/auth/callback', logout: '/auth/logout', profile: '/auth/profile', }, session: { rolling: true, rollingDuration: 24 * 60 * 60, // 24 hours in seconds absoluteDuration: 7 * 24 * 60 * 60, // 7 days in seconds }, }); ``` **Note:** Most configuration can be omitted - v4 uses sensible defaults. The middleware automatically mounts auth routes. --- ## Testing 1. Start your dev server: `npm run dev` 2. Visit `http://localhost:3000` 3. Click "Login" - redirects to Auth0 4. Complete authentication 5. Verify redirect back with user session 6. Test protected pages and API routes 7. Click "Logout" and verify session cleared --- ## Common Issues | Issue | Solution | |-------|----------| | "Missing required parameter: redirect_uri" | Ensure `APP_BASE_URL` is set correctly (v4 renamed from `AUTH0_BASE_URL`) | | "Invalid state" error | Clear cookies/storage. Verify callback URL in Auth0 dashboard matches `APP_BASE_URL/auth/callback` | | User session not persisting | Check `AUTH0_SECRET` is set and at least 32 characters | | API routes return 401 | Check session with `auth0.getSession()` in route handler | | Middleware loops infinitely | Ensure middleware matcher excludes `/auth/*` routes, not `/api/auth/*` | | Import errors for v3 helpers | v4 removed `withApiAuthRequired` and `withPageAuthRequired` - use `auth0.getSession()` | | Environment variable not recognized | v4 uses `AUTH0_DOMAIN` (no scheme) and `APP_BASE_URL`, not `AUTH0_ISSUER_BASE_URL` or `AUTH0_BASE_URL` | --- ## Security Considerations - **Keep secrets secure** - Never commit `.env.local` to version control - **Use HTTPS in production** - Auth0 requires secure callback URLs - **Rotate secrets regularly** - Update `AUTH0_SECRET` periodically - **Validate on server** - Always verify authentication server-side, not client-side - **Configure CORS** - Set allowed origins in Auth0 application settings --- ## Related Skills - `auth0-quickstart` - Initial Auth0 account setup - `auth0-migration` - Migrate from another auth provider - `auth0-mfa` - Add Multi-Factor Authentication - `auth0-organizations` - B2B multi-tenancy support - `auth0-passkeys` - Add passkey authentication --- ## References - [Auth0 Next.js SDK Documentation](https://auth0.com/docs/libraries/nextjs-auth0) - [Auth0 Next.js SDK GitHub](https://github.com/auth0/nextjs-auth0) - [Auth0 Next.js Quickstart](https://auth0.com/docs/quickstart/webapp/nextjs) - [Next