Next.js: The React Framework (App Router)Entry 13 of 16

Redirects and Proxy

redirect() sends the user elsewhere during rendering or in a Server Action. proxy.ts (called middleware.ts before Next.js 16) runs before a request reaches a route and can redirect, rewrite, or set headers.

Notes

  • redirect('/login') (307) and permanentRedirect('/new-url') (308) from next/navigation.
  • Static redirects belong in next.config.ts (redirects()).
  • proxy.ts sits at the project root (or src/), exports a proxy function, and uses a matcher to choose which paths it runs on.
  • Use the proxy for optimistic checks (is there a session cookie?). Do real authorization in the page, action, or data layer too.

What / Why / When

What

Request-time redirects and request interception.

Why

Protect routes, handle moved URLs, add headers.

When

Auth gates, locale redirects, legacy URLs.

Use case

Sending signed-out users from /dashboard to /login.

Code compare

Next.js
// proxy.tsimport { NextResponse, type NextRequest } from "next/server";​export function proxy(request: NextRequest) {  const session = request.cookies.get("session");  if (!session) {    return NextResponse.redirect(new URL("/login", request.url));  }  return NextResponse.next();}​export const config = {  matcher: ["/dashboard/:path*"],};
Next.js
// In a page or Server Actionimport { redirect } from "next/navigation";​const user = await getUser();if (!user) redirect("/login");

A functional guard returns a UrlTree to redirect:

Angular
// auth.guard.tsimport { inject } from '@angular/core';import { CanActivateFn, Router } from '@angular/router';import { AuthService } from './auth.service';​export const authGuard: CanActivateFn = () => {  const auth = inject(AuthService);  const router = inject(Router);  return auth.isLoggedIn() ? true : router.createUrlTree(['/login']);};​// app.routes.ts{ path: 'dashboard', canActivate: [authGuard], loadComponent: … },{ path: 'old-posts', redirectTo: 'posts' },

Request-level interception (before Angular renders) goes in server.ts as Express middleware.

Differences and gotchas

  • Guards run on the server during SSR and in the browser after hydration; the proxy runs only on the server, before rendering.
  • redirect() throws internally. Don't wrap it in try/catch, or the redirect is swallowed.
  • Next.js 16 renamed middleware to proxy; the old name still works but is deprecated.

Quick reference

Next.jsAngular
redirect('/login')Guard returning router.createUrlTree(['/login'])
redirects() in next.config{ path: 'old', redirectTo: 'new' }
proxy.ts + matcherExpress middleware in server.ts