Quick start guide Next.js with Auth0
Install @auth0/nextjs-auth0
npm i @auth0/nextjs-auth0
// create .env file
# Every value here is available under your application dashboard
# A long, secret value used to encrypt the session cookie
AUTH0_SECRET='LONG_RANDOM_VALUE'
# The base url of your application
AUTH0_BASE_URL='http://localhost:3000'
# The url of your Auth0 tenant domain
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com'
# Your Auth0 application's Client ID
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
# Your Auth0 application's Client Secret
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'
Create auth folders
Either at the app
or src
folder, please create folders api
> auth
> [auth0]
then the route.ts file in the [auth0] folder.
// api/auth/[auth0]/route.ts
import { handleAuth } from "@auth0/nextjs-auth0"
export const GET = handleAuth();
Note! Do not forget to add https://localhost:3000/api/auth/callback
to Allowed Callback Urls in Auth0 Application Dashboard.
Wrap with Auth0
Now you need to wrap your app in Layout.tsx:
// src/app/layout.tsx or app/layout.tsx
import { UserProvider } from "@auth0/nextjs-auth0/client";
...
<html>
<body className={inter.className}>
<UserProvider>{children}</UserProvider>
</body>
</html>
Now, you can use useUser
from @auth0/nextjs-auth0/client
to check your current user.
// anywhere inside UserProvider
import { useUser } from '@auth0/nextjs-auth0/client';
...
const { user, error, isLoading } = useUser();
// index.ts
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';
export default function Index() {
const { user, error, isLoading } = useUser();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
if (user) {
return (
<div>
Welcome {user.name}! <a href="/api/auth/logout">Logout</a>
</div>
);
}
return <a href="/api/auth/login">Login</a>;
}
Bonus: if you wrap in a context:
// src/app/layout.tsx or app/layout.tsx
import { UserProvider } from "@auth0/nextjs-auth0/client";
...
<body className={inter.className}>
<UserProvider>
<AppWrapper>
{children}
</AppWrapper>
</UserProvider>
</body>
// src/app/context.tsx
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';
import { redirect } from 'next/navigation';
import { createContext, useContext } from 'react';
const AppContext = createContext<any>(undefined);
export function AppWrapper({ children }: {
children: React.ReactNode
}) {
const { user, error, isLoading } = useUser();
if (isLoading) return <>loading...</>
if (!user) redirect("/api/auth/login")
return (
<AppContext.Provider
value={{
user,
}}
>
<main>
{children}
</main>
</AppContext.Provider >
);
}
export function useAppContext() {
return useContext(AppContext);
}
Best!
Guillaume Duhan