🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js proxy.ts

proxy.ts runs before a request reaches the page. It can let the request through or send it elsewhere.

The proxy file

The proxy logs the path, then checks the visit. The sign-in check itself is the next lesson.

import { NextResponse } from "next/server";
import { auth } from "@/auth";

// proxy.ts runs before every matched request. middleware.ts is the old name.
export default auth((req) => {
  console.log("[proxy] saw", req.nextUrl.pathname);
  if (req.nextUrl.pathname.startsWith("/my-books") && !req.auth) {
    return NextResponse.redirect(new URL("/sign-in", req.url));
  }
  return NextResponse.next();
});

export const config = {
  matcher: ["/my-books/:path*"],
};

The database, stated

The course data layer is Postgres in production. The JSON store stands in here, and the database was not started on this machine.

# Postgres 16 holds the users table in production.
# The JSON store stands in here; the database was not started.

Example

curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" http://localhost:3112/my-books

Key points

  • proxy.ts: the file that runs before a matched request, in the Next.js 16 way
  • middleware.ts is the old name. The file was renamed, and the old name no longer works.
  • A matcher lists the paths the proxy watches. Here it watches /my-books.
  • An unauthenticated visit to /my-books is sent to /sign-in. The page never runs.
  • A visit that passes the check goes through. The proxy returns next.
  • The build prints a Proxy line when a proxy file is present.
  • auth: the Auth.js helper that reads the session. It adds the session to the request as req.auth.

In this example, the check visits /my-books with no sign-in. The answer is 307, and the redirect points to /sign-in. The proxy saw the visit, found no session, and sent the reader to sign in before the page could run. The server log shows [proxy] saw /my-books on each visit. A signed-in visit passes through instead, as the next lesson shows.

Note

The database steps in this course use Postgres in Docker, stated here and not run: no Docker was on this machine, so the JSON store stands in.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

What is the Next.js 16 name for the file that runs before a request?