How to Use auth.js in Next.js for Authentication
To use
auth.js in Next.js, install the package, create an [...nextauth].js file in the pages/api/auth folder, and configure your authentication providers. Then, use the provided hooks like useSession in your components to manage user sessions.Syntax
The basic syntax involves importing NextAuth from auth.js and exporting it as a default API handler in pages/api/auth/[...nextauth].js. You configure providers inside the NextAuth call.
- providers: List of authentication providers like Google, GitHub.
- callbacks: Optional functions to control session and token behavior.
- pages: Customize sign-in, error pages.
javascript
import NextAuth from "next-auth"; import GoogleProvider from "next-auth/providers/google"; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], callbacks: { async session({ session, token }) { session.user.id = token.sub; return session; }, }, });
Example
This example shows a simple Next.js app using auth.js with Google authentication. It includes the API route setup and a component that shows the user's name when signed in or a sign-in button otherwise.
javascript
// pages/api/auth/[...nextauth].js import NextAuth from "next-auth"; import GoogleProvider from "next-auth/providers/google"; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], }); // pages/index.js import { useSession, signIn, signOut } from "next-auth/react"; export default function Home() { const { data: session } = useSession(); if (session) { return ( <div> <p>Signed in as {session.user.email}</p> <button onClick={() => signOut()}>Sign out</button> </div> ); } return ( <div> <p>Not signed in</p> <button onClick={() => signIn()}>Sign in</button> </div> ); }
Output
When signed out: Shows 'Not signed in' and a 'Sign in' button.
When signed in: Shows 'Signed in as user@example.com' and a 'Sign out' button.
Common Pitfalls
Common mistakes include:
- Not setting environment variables like
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRET. - Placing the API route file in the wrong folder (must be
pages/api/auth/[...nextauth].js). - Forgetting to wrap your app with
SessionProviderin_app.jsto enable session context. - Using outdated import paths or older versions of
auth.js.
Example of missing SessionProvider usage:
javascript
// pages/_app.js import { SessionProvider } from "next-auth/react"; export default function App({ Component, pageProps }) { return ( <SessionProvider session={pageProps.session}> <Component {...pageProps} /> </SessionProvider> ); }
Quick Reference
Remember these key points when using auth.js in Next.js:
- API route must be
pages/api/auth/[...nextauth].js. - Configure providers with client IDs and secrets from your OAuth apps.
- Wrap your app with
SessionProviderto access session data. - Use
useSessionhook to get current user info. - Use
signInandsignOutfunctions to control authentication flow.
Key Takeaways
Set up the API route at pages/api/auth/[...nextauth].js with your providers.
Wrap your app in SessionProvider to enable session context.
Use useSession hook to access user session data in components.
Always set environment variables for provider credentials.
Use signIn and signOut functions to manage authentication flow.