Menu

Proxy (proxy.ts)

Lesson 3: Proxy (proxy.ts)

What is Proxy?

proxy.ts is a file at the project root (or in src/) that runs before a request reaches a route. In Next.js 16, it replaces middleware.ts, which is deprecated. Proxy runs on the Node.js runtime.

Good uses Avoid
Redirecting signed-out users away from private sections (quick cookie check) Full authorisation or database checks (do these in the data layer)
Redirecting old URLs or by country/language Slow API calls on every request
Rewriting URLs for A/B tests Heavy computation
Adding security or tracking headers Replacing Route Handlers

Example

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

export function proxy(request: NextRequest) {
  const session = request.cookies.get('session')?.value;
  const { pathname } = request.nextUrl;

  // Optimistic check: send signed-out users to login
  if (pathname.startsWith('/dashboard') && !session) {
    const url = new URL('/login', request.url);
    url.searchParams.set('next', pathname);
    return NextResponse.redirect(url);
  }

  // Add a header to every matched response
  const response = NextResponse.next();
  response.headers.set('x-learnhub-region', 'in');
  return response;
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

How it works

Response Effect
NextResponse.next() Continue to the route (optionally with new headers)
NextResponse.redirect(url) Send the browser to a new URL
NextResponse.rewrite(url) Show content from another URL without changing the address bar
new Response(...) Respond directly, e.g. a 403
  • matcher limits which paths run the proxy. Exclude static files to avoid wasted work.
  • Proxy can read cookies and headers but should not do heavy work, because it runs on every matched request.
  • Migrating: rename middleware.ts to proxy.ts and the exported function to proxy. A codemod is available: npx @next/codemod@canary middleware-to-proxy .

Common mistakes

Mistake Effect Fix
Relying on proxy as the only security check Data can still be reached by other paths (e.g. Server Actions) Always check authorisation where data is read and changed
No matcher Runs for images and static files Add a matcher that excludes them
Redirect loops (/login redirects to /login) Browser error Exclude the target path from the condition
Database queries in proxy Slower responses everywhere Keep it to cookie and header checks

Key takeaways

  • proxy.ts runs before routing; use it for quick redirects, rewrites, and headers.
  • It is a first line of defence, not a replacement for authorisation in the data layer.

Try it: Write a proxy.ts that redirects signed-out users from /dashboard to /login?next=/dashboard.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details