Learn / Frameworks / Next.js / Middleware, Cookies and Sessions

Next.js · Lesson 8 of 15

Middleware, Cookies and Sessions

Run code at the edge for auth redirects and read cookies on the server.

  • Intermediate
  • 17 min read
  • 3 objectives

Before this lessonLesson 7: Streaming and Loading UI

What you will learn

  • Write middleware
  • Set httpOnly cookies
  • Protect a route group

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Middleware runs on the Edge before a request hits a page or route handler. Use it for redirects and header tweaks, not for database work.

A matcher and a redirect

// middleware.ts at the project root
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const session = req.cookies.get("session")?.value;
  if (!session) {
    const url = req.nextUrl.clone();
    url.pathname = "/login";
    url.searchParams.set("from", req.nextUrl.pathname);
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*", "/settings/:path*"] };

httpOnly cookies

Store session tokens in cookies the JavaScript on the page cannot read. Set them from a Route Handler or server action.

import { cookies } from "next/headers";

export async function POST() {
  const token = await createSession();          // your auth code
  const jar = await cookies();
  jar.set("session", token, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
  return Response.json({ ok: true });
}

Reading the user in a Server Component

import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export default async function Page() {
  const token = (await cookies()).get("session")?.value;
  const user = token ? await getUser(token) : null;
  if (!user) redirect("/login");
  return <h1>Hello {user.name}</h1>;
}
Up next · Lesson 9Databases with PrismaQuery Postgres from Server Components and mutate with server actions.