2.6 KiB
id, title
| id | title |
|---|---|
| example | Example |
Check out the example project
The easiest way to get started is to clone the example application and follow the instructions in the README.
You can find a live demo of the example project at next-auth-example.now.sh
Add to an existing project
The example code below shows how to add authentication to an existing Next.js project.
Add API route
To add NextAuth.js to a project create a file called [...nextauth].js in pages/api/auth.
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
const options = {
// Configure one or more authentication providers
providers: [
Providers.GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET
}),
// ...add more providers here
],
// A database is optional, but required to persist accounts in a database
database: process.env.DATABASE_URL,
}
export default (req, res) => NextAuth(req, res, options)
All requests to /api/auth/* (signin, callback, signout, etc) will automatically be handed by NextAuth.js.
:::tip See the options documentation for how to configure providers, databases and other options. :::
Add React Hook
The useSession() React Hook in the NextAuth.js client is the easiest way to check if someone is signed in.
import React from 'react'
import { signIn, signOut, useSession } from 'next-auth/client'
export default function Page() {
const [ session, loading ] = useSession()
return <>
{!session && <>
Not signed in <br/>
<button onClick={signIn}>Sign in</button>
</>}
{session && <>
Signed in as {session.user.email} <br/>
<button onClick={signOut}>Sign out</button>
</>}
</>
}
That's all the code you need to add authentication with NextAuth.js to a project!
You can use the useSession hook from a anywhere in your application (e.g. in a header component).
Configuration
When deploying to production, set the NEXTAUTH_URL environment variable to the canonical URL of your site.
NEXTAUTH_URL=https://example.com
To set environment variables on Vercel, you can use the dashboard or the now env command.
:::tip Check out the client documentation to see how you can improve the user experience and page performance by using the NextAuth.js client. :::