typescriptbeginner

Protected Page with Server Redirect

Server Component that checks auth status and redirects unauthenticated users before rendering any content.

typescript
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.