Authentication
NextAuth.js, session management, JWT, OAuth providers, and protected routes.
Overview
NextAuth.js provides authentication solutions for Next.js applications.
Key Concepts
- NextAuth.js — Complete authentication solution
- Session Strategies — JWT or database sessions
- OAuth Providers — Google, GitHub, Twitter, etc.
- Protected Routes — Middleware-based route protection
- Server Components — Access session in server components
Code Examples
// app/api/auth/[...nextauth]/route.js
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';
import Google from 'next-auth/providers/google';
const handler = NextAuth({
providers: [
GitHub({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }),
Google({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET })
],
callbacks: {
async session({ session, token }) {
session.user.id = token.sub;
return session;
}
}
});
export { handler as GET, handler as POST };
// Server component - access session
import { getServerSession } from 'next-auth';
async function DashboardPage() {
const session = await getServerSession();
if (!session) {
redirect('/api/auth/signin');
}
return <h1>Welcome, {session.user.name}</h1>;
}
// Protected route middleware
// middleware.js
export { default } from 'next-auth/middleware';
export const config = {
matcher: ['/dashboard/:path*']
};
Practice
Implement OAuth login with GitHub and Google, including protected dashboard.