Authentication & Authorization in Next.js
5 questions found
What is the difference between authentication and authorization in a Next.js application?
Beginner
Authentication confirms who a user is, usually through a login form or a third party sign in provider, while authorization decides what that authenticated user is allowed to do or see, such as whether they can access an admin page. Both work together to keep an app secure and personalized.
// Authentication: verifying login credentials
// Authorization: checking user.role === 'admin' before showing a page
Real-world example
A blogging platform authenticates a writer when they log in, then authorizes them to edit only their own posts while blocking them from editing posts written by other authors.
Common follow-ups: What tools are commonly used to add authentication to a Next.js app?;How do you protect a specific page so only logged in users can view it?
Middleware;Cookies & Session Management in Next.js
How would you protect a page in the App Router so only logged in users can access it?
Intermediate
You check the user's session at the top of a server component or in middleware, and redirect them to the login page immediately if no valid session is found, before any of the protected content is rendered or sent to the browser.
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
export default async function DashboardPage() {
const session = await getSession();
if (!session) {
redirect('/login');
}
return <p>Welcome, {session.user.name}</p>;
}
Real-world example
A dashboard page checks for a valid session on the server before rendering, sending unauthenticated visitors straight to the login page instead of showing them any dashboard content.
Common follow-ups: Should this check happen in middleware or inside the page component?;How do you keep the session check from running on every single request unnecessarily?
Middleware;Server Components
How can you use middleware to protect multiple routes at once for authentication?
Intermediate
Middleware runs before a request reaches a page, so you can check the user's session cookie there and redirect unauthenticated users away from any protected route defined in your matcher configuration, without repeating the same check inside every individual page.
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('session');
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'] };
Real-world example
An application protects every route under dashboard and settings using one middleware file, so new pages added under those folders are automatically protected without extra code.
Common follow-ups: What is the performance impact of running authentication checks in middleware?;How do you allow public pages to bypass this middleware check?
Middleware;Security Best Practices in Next.js
How do you implement role based authorization, where different users see different content based on their role?
Advanced
You store a role field on the user's account, such as admin or member, and check that role wherever access needs to be restricted, either in a server component before rendering or in an API route before processing a request, returning a forbidden response or a different view for unauthorized roles.
export default async function AdminPage() {
const session = await getSession();
if (session?.user.role !== 'admin') {
return <p>You do not have access to this page.</p>;
}
return <AdminDashboard />;
}
Real-world example
A support ticketing system shows regular employees only their own tickets, while showing managers a full view of every ticket, using the same page but with different data based on the logged in user's role.
Common follow-ups: Where should role information be stored, in the session or fetched fresh from the database?;How do you handle a user whose role changes while they are already logged in?
Security Best Practices in Next.js;Database Integration with Next.js
What are best practices for securely storing and validating authentication tokens in a Next.js app?
Advanced
Store authentication tokens in secure, httpOnly cookies so they cannot be accessed by client side JavaScript, always use HTTPS in production, set a reasonable expiration time, and verify token signatures on the server for every protected request rather than trusting client provided data.
res.setHeader('Set-Cookie', `session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/`);
Real-world example
A banking application stores its session token in an httpOnly secure cookie, preventing malicious scripts from stealing the token even if they somehow get injected into the page.
Common follow-ups: What is the difference between storing a token in a cookie versus local storage?;How often should authentication tokens be refreshed or rotated?
Security Best Practices in Next.js;Cookies & Session Management in Next.js