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) andpermanentRedirect('/new-url')(308) fromnext/navigation.- Static redirects belong in
next.config.ts(redirects()). proxy.tssits at the project root (orsrc/), exports aproxyfunction, and uses amatcherto 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
/dashboardto/login.
Code compare
// 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*"],};// 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:
// 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 intry/catch, or the redirect is swallowed.- Next.js 16 renamed
middlewaretoproxy; the old name still works but is deprecated.
Quick reference
| Next.js | Angular |
|---|---|
redirect('/login') | Guard returning router.createUrlTree(['/login']) |
redirects() in next.config | { path: 'old', redirectTo: 'new' } |
proxy.ts + matcher | Express middleware in server.ts |