Back to results for “Authentication”
Next.js › Authentication & Authorization in Next.js

How would you protect a page in the App Router so only logged in users can access it?

Intermediate

Answer

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?