patterntypescriptMajor
Protected Routes Pattern in Next.js App Router
Viewed 0 times
next-auth v5 / Auth.js, Next.js 14+
protected routesrequireAuthredirectserver componentmiddlewarenext.js auth
Problem
Protecting pages so unauthenticated users are redirected to login requires a consistent approach. Doing it ad-hoc in every page component is error-prone and easy to forget.
Solution
Create a reusable requireAuth server-side helper that calls auth(), checks for a session, and calls redirect('/login') if absent. Call it at the top of every protected Server Component's data-loading function. Optionally, reinforce with middleware for defense in depth.
Why
Server-side redirect happens before any content is rendered or sent to the client, so protected data never reaches the browser. Middleware adds a fast-path check at the edge before the request hits the server.
Gotchas
- Client Components cannot use the redirect() function from next/navigation during render — only Server Components and Server Actions can
- Middleware runs on every request including static files unless correctly scoped with a matcher
- Don't rely solely on middleware for auth — it can be bypassed if the route handler is invoked directly
Code Snippets
requireAuth helper for Server Components
import { auth } from '@/auth';
import { redirect } from 'next/navigation';
export async function requireAuth() {
const session = await auth();
if (!session?.user) redirect('/login');
return session;
}
// Usage in a protected page
export default async function DashboardPage() {
const session = await requireAuth();
return <div>Welcome, {session.user.email}</div>;
}Revisions (0)
No revisions yet.