Next.js Course
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?

Flash Cards

Question

Best way to protect 50?

Click to reveal answer
Answer

Using Next.js Middleware. You can protect an entire folder structure (like `/dashboard/*`) with one line of config, rather than adding checks to 50 individual files.

Question

Why not useEffect?

Click to reveal answer
Answer

Security and UX. Client components render HTML immediately. If you use `useEffect` to check auth, the user will see a flash of the protected data for a split second before the JavaScript executes and kicks them out. Protection must happen on the server.