Protected Page with Server Redirect
Server Component that checks auth status and redirects unauthenticated users before rendering any content.
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
async function getUser() {
const cookieStore = await cookies();
const token = cookieStore.get('auth-token')?.value;
if (!token) return null;
// Replace with your auth verification
try {
const res = await fetch(process.env.AUTH_API + '/me', {
headers: { Authorization: `Bearer ${token}` },
cache: 'no-store',
});
if (!res.ok) return null;
return res.json();
} catch {
return null;
}
}
export default async function DashboardPage() {
const user = await getUser();
if (!user) redirect('/login?callbackUrl=/dashboard');
return (
<div>
<h1>Dashboard</h1>
<p>Welcome, {user.name}</p>
</div>
);
}
// This pattern ensures:
// 1. No client-side flash of protected content
// 2. Auth check happens on the server
// 3. Redirect is instant (before any HTML is sent)Use Cases
- Dashboard pages
- User profile pages
- Admin panels
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.