Next.js course ยท Module 7: Authentication and Authorization
Authentication basics in Next.js applications
In this lesson8
Authentication is a fundamental aspect of modern web applications. It allows you to verify user identity, which is essential for personalizing experiences, protecting data, and providing features only to authorized users. In this module, we will learn the basics of implementing authentication in Next.js applications, which combines the benefits of server-side rendering (SSR) and client-side rendering.
What is authentication and why is it important?
Authentication is the process of verifying a user's identity. It is a key element of web application security because:
- Protects user data - ensures that personal information is accessible only to its owners
- Enables personalization - allows tailoring the experience to a specific user
- Controls access - determines which resources and features a user can access
- Ensures accountability - allows tracking who performed specific actions and when
Authentication vs. Authorization
It is important to distinguish between two related but separate concepts:
- Authentication - verifying the user's identity ("Are you who you claim to be?")
- Authorization - determining what an authenticated user can do ("Do you have permission to do this?")
In many cases, both processes are interconnected, but they serve different functions in the security architecture.
Authentication specifics in Next.js
Next.js offers a hybrid rendering model, which has a significant impact on authentication implementation:
- Server-Side Rendering (SSR) - enables authentication verification before sending the page to the client
- Static Site Generation (SSG) - requires additional client-side verification for protected content
- App Router - provides new, dedicated mechanisms for handling authentication
Basic authentication models
Several main authentication models can be applied in Next.js applications:
1. Session-based authentication
A traditional approach based on maintaining session state on the server:
// Example API route for session-based login
import { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '../auth/[...nextauth]';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session) {
return res.status(401).json({ message: 'Unauthorized' });
}
// User authenticated, can proceed
return res.status(200).json({ user: session.user });
}2. Token-based authentication (JWT)
A popular approach using JWT (JSON Web Tokens):
// Example API route for JWT token verification
import { NextApiRequest, NextApiResponse } from 'next';
import jwt from 'jsonwebtoken';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const { authorization } = req.headers;
if (!authorization || !authorization.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Unauthorized' });
}
const token = authorization.replace('Bearer ', '');
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!);
// Token valid, can proceed
return res.status(200).json({ user: decoded });
} catch (error) {
return res.status(401).json({ message: 'Invalid token' });
}
}3. Authentication with external providers (OAuth)
Using external services like Google, Facebook, or GitHub:
// Example NextAuth.js configuration with Google authentication
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!
})
],
// Additional configuration...
});Implementing authentication in the Next.js App Router
In newer versions of Next.js (13+) with App Router, the authentication approach has been improved. Below are the basic steps:
1. Configuring the authentication provider
First, we need to configure the authentication provider. In this example, we will use Auth.js (formerly NextAuth.js):
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { compare } from 'bcrypt';
import { prisma } from '@/lib/prisma';
export const authOptions = {
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
const user = await prisma.user.findUnique({
where: {
email: credentials.email
}
});
if (!user) {
return null;
}
const isPasswordValid = await compare(
credentials.password,
user.password
);
if (!isPasswordValid) {
return null;
}
return {
id: user.id,
email: user.email,
name: user.name
};
}
})
],
pages: {
signIn: '/login',
signOut: '/logout',
error: '/login',
},
session: {
strategy: 'jwt'
}
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };2. Creating login and registration components
Next, we need a user interface for login:
// app/login/page.tsx
'use client';
import { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/navigation';
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError('');
try {
const result = await signIn('credentials', {
redirect: false,
email,
password
});
if (result?.error) {
setError('Invalid email or password');
} else {
router.push('/dashboard');
router.refresh();
}
} catch (error) {
setError('An error occurred during login');
} finally {
setLoading(false);
}
}
return (
<div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">Login</h1>
{error && (
<div className="mb-4 p-3 bg-red-100 text-red-700 rounded">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="email" className="block text-sm font-medium mb-1">
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded"
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium mb-1">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 disabled:opacity-50"
>
{loading ? 'Logging in...' : 'Log in'}
</button>
</form>
</div>
);
}And a registration page:
// app/register/page.tsx
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export default function RegisterPage() {
const router = useRouter();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError('');
// Validate form
if (password !== confirmPassword) {
setError('Passwords do not match');
setLoading(false);
return;
}
try {
const response = await fetch('/api/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email, password })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'An error occurred during registration');
}
// Registration successful, redirect to login page
router.push('/login?registered=true');
} catch (error) {
setError(error instanceof Error ? error.message : 'An error occurred');
} finally {
setLoading(false);
}
}
return (
<div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">Registration</h1>
{error && (
<div className="mb-4 p-3 bg-red-100 text-red-700 rounded">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium mb-1">
Full name
</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded"
/>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium mb-1">
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded"
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium mb-1">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
className="w-full px-3 py-2 border border-gray-300 rounded"
/>
</div>
<div>
<label htmlFor="confirmPassword" className="block text-sm font-medium mb-1">
Confirm password
</label>
<input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 disabled:opacity-50"
>
{loading ? 'Registering...' : 'Sign up'}
</button>
</form>
</div>
);
}3. Implementing the registration API endpoint
To enable registration, we need an API endpoint:
// app/api/register/route.ts
import { NextResponse } from 'next/server';
import { hash } from 'bcrypt';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';
// Validation schema
const UserSchema = z.object({
name: z.string().min(2, 'First name must be at least 2 characters'),
email: z.string().email('Invalid email address'),
password: z.string().min(8, 'Password must be at least 8 characters')
});
export async function POST(request: Request) {
try {
const body = await request.json();
// Validate data
const result = UserSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ message: result.error.errors[0].message },
{ status: 400 }
);
}
const { name, email, password } = result.data;
// Check if user already exists
const existingUser = await prisma.user.findUnique({
where: { email }
});
if (existingUser) {
return NextResponse.json(
{ message: 'A user with this email address already exists' },
{ status: 409 }
);
}
// Hash the password
const hashedPassword = await hash(password, 10);
// Create new user
const user = await prisma.user.create({
data: {
name,
email,
password: hashedPassword
}
});
// Return response without password
const { password: _, ...userWithoutPassword } = user;
return NextResponse.json(
{ message: 'Registration completed successfully', user: userWithoutPassword },
{ status: 201 }
);
} catch (error) {
console.error('Registration error:', error);
return NextResponse.json(
{ message: 'A server error occurred' },
{ status: 500 }
);
}
}4. Securing protected pages
To protect pages that should only be accessible to logged-in users, we can use middleware:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
// Check if user is logged in
if (!token) {
const url = new URL('/login', request.url);
url.searchParams.set('callbackUrl', request.nextUrl.pathname);
return NextResponse.redirect(url);
}
return NextResponse.next();
}
// Define paths that should be protected
export const config = {
matcher: ['/dashboard/:path*', '/profile/:path*', '/settings/:path*']
};5. Displaying user data and managing sessions
To use information about the logged-in user in a component, we can use the hook useSession:
// components/ProfileSection.tsx
'use client';
import { useSession } from 'next-auth/react';
import { signOut } from 'next-auth/react';
export default function ProfileSection() {
const { data: session, status } = useSession();
if (status === 'loading') {
return <div>Loading...</div>;
}
if (status === 'unauthenticated' || !session) {
return <div>You are not logged in</div>;
}
return (
<div className="p-4 bg-white rounded shadow">
<h2 className="text-xl font-bold mb-4">Your profile</h2>
<p>Hello, {session.user?.name || 'user'}!</p>
<p>Email: {session.user?.email}</p>
<button
onClick={() => signOut({ callbackUrl: '/' })}
className="mt-4 px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
>
Log out
</button>
</div>
);
}6. Initializing SessionProvider for the entire application
For authentication to work properly, we need to add SessionProvider at the layout level:
// app/providers.tsx
'use client';
import { SessionProvider } from 'next-auth/react';
import { ReactNode } from 'react';
export function Providers({ children }: { children: ReactNode }) {
return <SessionProvider>{children}</SessionProvider>;
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}Security mechanisms
When implementing authentication, it is important to keep in mind several key security mechanisms:
1. Secure password storage
Never store passwords in plain text! Always use hashing functions such as bcrypt:
import { hash, compare } from 'bcrypt';
// Hashing password during registration
const hashedPassword = await hash(password, 10);
// Verifying password during login
const isValid = await compare(password, hashedPassword);2. Protection against CSRF attacks
Cross-Site Request Forgery (CSRF) is a type of attack that exploits an authenticated user's session to perform unauthorized actions. Next.js and NextAuth.js provide some protections by default, but it is worth ensuring additional protection:
// Adding a CSRF token to the form
export default function LoginForm() {
const csrfToken = await getCsrfToken();
return (
<form method="post" action="/api/auth/callback/credentials">
<input name="csrfToken" type="hidden" defaultValue={csrfToken} />
{/* Rest of the form */}
</form>
);
}3. HTTPS implementation
Using encrypted HTTPS connections is essential for protecting authentication credentials and session tokens. In a production environment, make sure your application is accessible only via HTTPS.
4. JWT token expiration
If you use JWT tokens, set an appropriate expiration time to limit risk in case of token theft:
// JWT token expiration configuration in NextAuth.js
export const authOptions = {
// ... other options
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // 30 days
},
jwt: {
secret: process.env.JWT_SECRET,
maxAge: 30 * 24 * 60 * 60, // 30 days
}
};Common challenges and solutions
Problem: Enforcing authentication on static pages (SSG)
A challenge can be securing pages that are statically generated during build:
Solution: Add an additional client-side verification layer:
'use client';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
export default function ProtectedPage() {
const { status } = useSession();
const router = useRouter();
useEffect(() => {
if (status === 'unauthenticated') {
router.push('/login');
}
}, [status, router]);
if (status === 'loading') {
return <div>Loading...</div>;
}
if (status === 'unauthenticated') {
return null; // Instead of rendering content, redirect to login page
}
// Actual content of the protected page
return (
<div>
<h1>Protected page</h1>
{/* Rest of content */}
</div>
);
}Problem: Different user roles
Sometimes we need different access levels for users:
Solution: Extend the token/session with role information and implement role checking:
// Extending NextAuth types
declare module 'next-auth' {
interface Session {
user: {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
role: string;
};
}
interface User {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
role: string;
}
}
// Using role information
function canAccessAdmin(session: Session | null) {
return session?.user?.role === 'admin';
}
// In the component
const { data: session } = useSession();
const isAdmin = session?.user?.role === 'admin';
if (!isAdmin) {
return <div>Access denied. This section is for administrators only.</div>;
}Summary
Authentication in Next.js can be implemented in many ways, but the most commonly used approaches include:
- NextAuth.js / Auth.js - a comprehensive solution offering integration with many authentication providers
- Custom JWT solution - for non-standard requirements
- External services - e.g., Firebase Auth, Auth0, Clerk
Choosing the right solution depends on the specific requirements of your application, such as:
- Need for integration with external providers (Google, Facebook, etc.)
- Data ownership requirements
- Complexity of the permissions and roles model
- Scalability
In the following modules, we will look at more advanced aspects of authentication, including detailed NextAuth.js implementation, session and token management, route protection using middleware, and security topics.
Code for this lesson: App.tsx
// Demo: Authentication basics in Next.js applications
// Overview of auth strategies: JWT, Session, OAuth
import React, { useState } from 'react';
// Authentication in Next.js:
// 1. JWT (JSON Web Token) - token in the Authorization header
// 2. Session-based - cookie with session ID, data on the server
// 3. OAuth - delegation to external provider (Google, GitHub)
// 4. Auth.js (NextAuth) - the most popular library
interface AuthStrategy {
name: string;
description: string;
flow: string[];
pros: string[];
cons: string[];
color: string;
nextjsCode: string;
}
const strategies: AuthStrategy[] = [
{
name: 'JWT (Stateless)',
description: 'Token containing encoded user data. Server does not store session state.',
flow: ['User logs in (email + password)', 'Server generates JWT token', 'Token sent in every request (Header)', 'Server verifies token signature'],
pros: ['Scalable - no server state', 'Works with microservices', 'Easy to implement'],
cons: ['Cannot be easily revoked', 'Token can be large', 'Risk of token theft'],
color: '#ff9800',
nextjsCode: "// middleware.ts\nimport { jwtVerify } from 'jose';\n\nexport async function middleware(req) {\n const token = req.headers.get('authorization');\n const { payload } = await jwtVerify(token, secret);\n // payload.userId, payload.role...\n}",
},
{
name: 'Session (Stateful)',
description: 'The server stores session data. The client receives a cookie with the session ID.',
flow: ['User logs in', 'Server creates session in database/Redis', 'Cookie with session ID sent to client', 'On every request server checks session'],
pros: ['Easy revocation (delete session)', 'Less data in cookie', 'More secure (HttpOnly cookies)'],
cons: ['Requires storage (Redis/DB)', 'Harder to scale', 'Sticky sessions'],
color: '#64ffda',
nextjsCode: "// auth.ts (Auth.js v5)\nimport NextAuth from 'next-auth';\nimport Credentials from 'next-auth/providers/credentials';\n\nexport const { auth, signIn, signOut } = NextAuth({\n providers: [Credentials({...})],\n session: { strategy: 'database' },\n});",
},
{
name: 'OAuth 2.0',
description: 'Authentication delegation to external provider (Google, GitHub, etc.).',
flow: ['User clicks "Sign in with Google"', 'Redirect to Google login', 'Google confirms identity', 'Callback with authorization code', 'Server exchanges code for token'],
pros: ['No password management', 'Trusted provider', 'Fast login for user'],
cons: ['Dependency on external service', 'Complex flow (redirects)', 'Requires app registration'],
color: '#7c4dff',
nextjsCode: "// auth.ts\nimport NextAuth from 'next-auth';\nimport Google from 'next-auth/providers/google';\nimport GitHub from 'next-auth/providers/github';\n\nexport const { handlers, auth } = NextAuth({\n providers: [Google, GitHub],\n});\n\n// app/api/auth/[...nextauth]/route.ts\nexport const { GET, POST } = handlers;",
},
];
function FlowDiagram({ steps, color }: { steps: string[]; color: string }) {
return (
<div style={{ display: 'grid', gap: '8px', marginTop: '12px' }}>
{steps.map((step, i) => (
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{
width: '28px', height: '28px', borderRadius: '50%',
background: `${color}20`, color, flexShrink: 0,
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: '0.8rem', fontWeight: 'bold',
}}>{i + 1}</div>
<span style={{ color: '#b0bec5', fontSize: '0.85rem' }}>{step}</span>
</div>
))}
</div>
);
}
export default function AuthIntroduction() {
const [activeStrategy, setActiveStrategy] = useState(0);
const s = strategies[activeStrategy];
return (
<div style={{
background: '#0f0f23', minHeight: '100vh', padding: '24px',
color: '#fff', fontFamily: 'system-ui, sans-serif',
}}>
<h1 style={{ color: '#64ffda', marginBottom: '4px' }}>Authentication in Next.js</h1>
<p style={{ color: '#b0bec5', marginBottom: '20px' }}>
JWT vs Session vs OAuth - strategy comparison
</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px', marginBottom: '24px' }}>
{strategies.map((st, i) => (
<button key={st.name} onClick={() => setActiveStrategy(i)} style={{
background: i === activeStrategy ? `${st.color}15` : 'rgba(255,255,255,0.02)',
border: `2px solid ${i === activeStrategy ? st.color : 'rgba(255,255,255,0.08)'}`,
color: i === activeStrategy ? st.color : '#78909c',
padding: '14px', borderRadius: '10px', cursor: 'pointer',
textAlign: 'center', fontWeight: 500,
}}>
{st.name}
</button>
))}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
<div>
<div style={{
background: `${s.color}08`, border: `1px solid ${s.color}30`,
borderRadius: '12px', padding: '20px',
}}>
<h3 style={{ color: s.color, marginBottom: '8px' }}>{s.name}</h3>
<p style={{ color: '#b0bec5', fontSize: '0.9rem', lineHeight: 1.5, marginBottom: '0' }}>
{s.description}
</p>
<FlowDiagram steps={s.flow} color={s.color} />
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginTop: '16px' }}>
<div style={{ background: 'rgba(76,175,80,0.08)', borderRadius: '10px', padding: '14px' }}>
<h4 style={{ color: '#4caf50', marginBottom: '8px', fontSize: '0.85rem' }}>Pros</h4>
{s.pros.map(p => (
<p key={p} style={{ color: '#b0bec5', fontSize: '0.8rem', margin: '4px 0' }}>+ {p}</p>
))}
</div>
<div style={{ background: 'rgba(244,67,54,0.08)', borderRadius: '10px', padding: '14px' }}>
<h4 style={{ color: '#f44336', marginBottom: '8px', fontSize: '0.85rem' }}>Cons</h4>
{s.cons.map(c => (
<p key={c} style={{ color: '#b0bec5', fontSize: '0.8rem', margin: '4px 0' }}>- {c}</p>
))}
</div>
</div>
</div>
<div style={{
background: 'rgba(0,0,0,0.3)', borderRadius: '12px', padding: '20px',
}}>
<h4 style={{ color: s.color, marginBottom: '12px' }}>Implementation in Next.js</h4>
<pre style={{
margin: 0, color: '#b0bec5', fontSize: '0.8rem',
lineHeight: 1.6, whiteSpace: 'pre-wrap',
}}>
{s.nextjsCode}
</pre>
</div>
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?