Sessions, OAuth, Magic Links — One Library
Auth With Auth.js
Auth.js (formerly NextAuth) plugs into App Router with a single handler and a couple of provider configs.
What you'll learn
- Install `next-auth@beta` and configure providers
- Create `app/api/auth/[...nextauth]/route.ts`
- Use `auth()` to read the session in server components
Auth.js is the most widely used auth library for Next. It supports OAuth, email magic links, credentials, and sessions out of the box.
Install
npm i next-auth@beta Configure Providers
// auth.ts
import NextAuth from 'next-auth'
import GitHub from 'next-auth/providers/github'
export const { auth, handlers, signIn, signOut } = NextAuth({
providers: [
GitHub({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
],
}) Mount the Handler
// app/api/auth/[...nextauth]/route.ts
export { GET, POST } from '@/auth'
// Wait — handlers is a single object, so:
// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth'
export const { GET, POST } = handlers Auth.js owns the entire /api/auth/* URL space — sign-in, callback, sign-out, session
endpoints.
Read the Session
// app/profile/page.tsx
import { auth } from '@/auth'
export default async function Page() {
const session = await auth()
if (!session) return <p>Please sign in.</p>
return <p>Hello, {session.user?.name}</p>
} auth() returns the session for the current request — cookies, CSRF, and decoding are
all handled.