Next.js
/Beginner
Protected Routes
Definition
Application URLs that are strictly locked behind an authentication check, preventing anonymous users from accessing them.
Explain Like I'm New
If you are not logged in, you cannot view the `/dashboard`. If you try to go there, the system violently kicks you back to the `/login` page.
Real World Example
Protecting a user's private settings page or billing history.
Common Use Cases
- •Gated content
- •User dashboards
Interactive Example
// app/dashboard/page.tsx import { redirect } from 'next/navigation'; import { getAuth } from '@/lib/auth'; export default async function SecureDashboard() { // 1. SERVER-SIDE PROTECTION // This happens on the server. The user never sees a flash of content. const user = await getAuth(); if (!user) { // 2. Instantly halt rendering and redirect to login redirect('/login'); } // 3. Safe to render private data return <h1>Secret Financial Data for {user.name}</h1>; }
Interview Questions
basic
- What is the best way to protect 50 different routes at the exact same time in Next.js?
intermediate
- Why shouldn't you protect routes solely using a `useEffect` hook in a Client Component?