Next.js Lesson 10: Authentication
NextAuth.js (now Auth.js) is the go-to authentication library for Next.js. It handles OAuth (Google, GitHub), email/password, sessions, and JWT — all in a few lines of config.
npm install next-auth@beta
Setup
// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import Credentials from "next-auth/providers/credentials";
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
GitHub, // needs GITHUB_ID and GITHUB_SECRET in .env
Google, // needs GOOGLE_ID and GOOGLE_SECRET in .env
Credentials({
async authorize({ email, password }) {
const user = await db.findUser(email);
if (user && await bcrypt.compare(password, user.password)) {
return user;
}
return null;
}
})
],
callbacks: {
session: ({ session, token }) => ({
...session,
user: { ...session.user, id: token.sub }
})
}
});
export const { GET, POST } = handlers;
Using Auth in Components
// Server Component
import { auth } from "@/auth";
export default async function Profile() {
const session = await auth();
if (!session) return <p>Not logged in</p>;
return <p>Hello, {session.user?.name}!</p>;
}
// Protect a route with Middleware (middleware.ts)
export { auth as middleware } from "@/auth";
export const config = {
matcher: ["/dashboard/:path*", "/profile/:path*"]
};
🏋️ Practice Task
Set up Next.js with NextAuth. Add GitHub OAuth (register at github.com/settings/developers). Create a Sign In button that calls signIn(“github”). Show user info (avatar + name) when logged in. Create a protected /dashboard route. Add middleware to redirect unauthenticated users to /login.
💡 Hint: Create .env.local with GITHUB_ID, GITHUB_SECRET, AUTH_SECRET (run: npx auth secret).