Next.js · Lesson 11 of 15
Authentication with Auth.js
Sign in with OAuth or credentials and read the session on server and client.
- Intermediate
- 17 min read
- 3 objectives
Before this lessonLesson 10: Errors, Parallel and Intercepting Routes
What you will learn
- Configure Auth.js
- Protect a page
- Read the session
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Auth.js (next-auth v5) handles OAuth, magic links and credentials, and exposes the session on the server and in Client Components.
Config
// auth.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [GitHub],
});
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;Protect a page
import { auth } from "@/auth";
import { redirect } from "next/navigation";
export default async function Account() {
const session = await auth();
if (!session?.user) redirect("/api/auth/signin");
return <p>Signed in as {session.user.email}</p>;
}Buttons
import { signIn, signOut } from "@/auth";
export function SignIn() {
return (
<form action={async () => { "use server"; await signIn("github"); }}>
<button type="submit">Sign in</button>
</form>
);
}On the client, wrap the tree with SessionProvider and call useSession() only where you need interactivity (an avatar menu). Prefer auth() in Server Components so the session is not a client waterfall.
