Que fait auth0-nextjs ?
À utiliser pour ajouter l'authentification aux applications Next.js (connexion, déconnexion, pages protégées, middleware, composants serveur) - prend en charge App Router et Pages Router avec le SDK @auth0/nextjs-auth0.
Configuration
Installez le SDK :
npm install @auth0/nextjs-auth0
Définissez les variables d'environnement suivantes dans .env.local :
AUTH0_SECRET='votre-secret' # Utilisez 'openssl rand -hex 32' pour générer
AUTH0_BASE_URL='http://localhost:3000' # En production, mettez l'URL réelle
AUTH0_ISSUER_BASE_URL='https://votre-nom-de-domaine.auth0.com'
AUTH0_CLIENT_ID='votre-client-id'
AUTH0_CLIENT_SECRET='votre-client-secret'
Utilisation
App Router
Créez un fichier app/api/auth/[auth0]/route.js :
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();
Pour protéger une page ou un composant serveur :
import { getSession } from '@auth0/nextjs-auth0';
export default async function Home() {
const session = await getSession();
if (!session) {
return (
<div>
<a href="/api/auth/login">Connexion</a>
</div>
);
}
return <div>Bienvenue {session.user.name} !</div>;
}
Pages Router
Créez pages/api/auth/[...auth0].js :
import { handleAuth } from '@auth0/nextjs-auth0';
export default handleAuth();
Protégez une page dans _app.js :
import { UserProvider } from '@auth0/nextjs-auth0/client';
export default function App({ Component, pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
Middleware
Créez un fichier middleware.js à la racine du projet :
import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/middleware';
export default withMiddlewareAuthRequired();
// Pour restreindre à des chemins spécifiques :
export const config = {
matcher: '/dashboard/:path*',
};
Ressources
- Documentation officielle : auth0.com/docs/quickstart/webapp/nextjs
- SDK GitHub : github.com/auth0/nextjs-auth0
- Support des versions : Next.js 12+