Wire up authentication with Auth.js in a Next.js app — configure a provider, expose the route handlers, and read the session on the server with a single call.
Where: Auth.js centralizes config in one file and exposes ready-made handlers. You list the providers you want, and it generates the sign-in routes, callbacks, and session cookies. This is the whole core setup for GitHub login.
// auth.ts
import NextAuth from 'next-auth'
import GitHub from 'next-auth/providers/github'
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [GitHub], // reads GITHUB_ID / GITHUB_SECRET from your env
})
// app/api/auth/[...nextauth]/route.ts
// export const { GET, POST } = handlersWhy: once configured, you check who is signed in with a single call on the server, and trigger sign-in or sign-out from a form — no manual cookie or token handling.
import { auth, signIn, signOut } from '@/auth'
export default async function Nav() {
const session = await auth() // null if signed out
if (!session) {
return (
<form action={async () => {
'use server'
await signIn('github')
}}>
<button>Sign in with GitHub</button>
</form>
)
}
return (
<form action={async () => {
'use server'
await signOut()
}}>
<span>{session.user?.name}</span>
<button>Sign out</button>
</form>
)
}