Sikau

Next.js · Day 17 · about 30 min

Proxy and protected pages

Run code before a request: redirects and simple auth checks.

Stop at the door

Some pages are for staff only. proxy (proxy.js at the project root — called *middleware* before Next.js 16) runs before matching requests, so it can redirect visitors who aren't signed in before the page even renders.

proxy.js

import { NextResponse } from "next/server";

export function proxy(request) {
  const session = request.cookies.get("session");
  if (!session) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/admin/:path*",
};
  • Proxy is for quick, *optimistic* checks. Still verify the user in the page or server action that reads or changes data.
  • For simple fixed redirects, use redirects in next.config instead.
  • Auth libraries (Auth.js, Clerk, Better Auth) handle sessions and give you helpers for this.

The rest of this lesson

  • What proxy is good forexplain
  • Defence in depthexplain
  • Does it run?predict
  • Proxy responsesmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js