Skip to content
Guest
Next.js · Course Syllabus Show lessons
Mutations & Auth · 10 min read · Intermediate

Middleware, HttpOnly Cookies & Auth Guards

Protect private dashboards using HttpOnly signed session cookies, middleware redirects, and server-side session checks.

What you'll learn

  • Store session tokens in HttpOnly, Secure, SameSite=Lax cookies instead of localStorage
  • Use middleware.ts for lightweight optimistic redirects
  • Always re-verify session authorization inside Server Components and Actions

Overview

Protect private dashboards using HttpOnly signed session cookies, middleware redirects, and server-side session checks.

Next.js App Router unifies server rendering, streaming, type-safe mutations, and edge-ready caching inside a single React + TypeScript codebase.

Production Code Example

// middleware.ts
import { NextResponse, type NextRequest } from 'next/server';

export function middleware(req: NextRequest) {
  const hasSession = req.cookies.has('devpath_session');
  if (!hasSession && req.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  return NextResponse.next();
}

Key Takeaways

  • Store session tokens in HttpOnly, Secure, SameSite=Lax cookies instead of localStorage
  • Use middleware.ts for lightweight optimistic redirects
  • Always re-verify session authorization inside Server Components and Actions

Quick Check

Check Your Understanding

Score: 0 / 1

1. Why are `HttpOnly` cookies safer than `localStorage` for storing authentication session tokens?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind