typescriptbeginner
Protected Page with Server Redirect
Server Component that checks auth status and redirects unauthenticated users before rendering any content.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Next.js Middleware for Authentication
Protect routes with Next.js middleware using token verification and role-based redirects.
Best for: Protecting authenticated routes at the edge
#nextjs#middleware
typescriptadvanced
Middleware Chain Pattern
Compose multiple middleware functions for auth, rate limiting, and geolocation in Next.js middleware.
Best for: Auth guard middleware
#nextjs#middleware
typescriptbeginner
Redirect After Server Action
Use redirect() inside a server action to navigate after form submission in Next.js App Router.
Best for: form submissions
#nextjs#server-actions
typescriptadvanced
Middleware Geo-based Redirect
Redirect users based on their geographic location using Next.js edge middleware.
Best for: internationalization
#nextjs#middleware