How to Use next-auth in Next.js for Authentication
To use
next-auth in Next.js, install the package, create an API route for authentication, and configure providers in [...nextauth].js. Then, use the useSession hook in your components to access user session data.Syntax
The main setup involves creating a file pages/api/auth/[...nextauth].js where you configure NextAuth with authentication providers and options. Use the useSession hook in your React components to get the current user's session.
NextAuth(): Initializes authentication with config.providers: List of sign-in providers like Google, GitHub.useSession(): React hook to get session info in components.
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, }), ], })
Example
This example shows a basic Next.js app using next-auth with Google sign-in. It includes the API route setup and a simple page 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: "Not signed in" with a Sign in button.
When signed in: "Signed in as user@example.com" with a Sign out button.
Common Pitfalls
Common mistakes include:
- Not setting environment variables
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRET. - Forgetting to wrap your app with
SessionProviderin_app.jsto enable session context. - Using
signInorsignOutwithout importing them fromnext-auth/react. - Not protecting pages that require authentication.
javascript
/* Wrong: Missing SessionProvider in _app.js */ // pages/_app.js export default function App({ Component, pageProps }) { return <Component {...pageProps} /> } /* Right: Wrap with SessionProvider */ import { SessionProvider } from 'next-auth/react' export default function App({ Component, pageProps }) { return ( <SessionProvider session={pageProps.session}> <Component {...pageProps} /> </SessionProvider> ) }
Quick Reference
| Feature | Usage |
|---|---|
| Install next-auth | npm install next-auth |
| Create API route | pages/api/auth/[...nextauth].js |
| Add providers | Configure in NextAuth({ providers: [...] }) |
| Use session in components | const { data: session } = useSession() |
| Sign in/out | import { signIn, signOut } from 'next-auth/react' |
Key Takeaways
Install next-auth and create the API route at pages/api/auth/[...nextauth].js.
Configure authentication providers like Google with client ID and secret.
Wrap your app with SessionProvider in _app.js to enable session context.
Use useSession hook to access user session data in components.
Use signIn and signOut functions from next-auth/react to handle login/logout.