More Next.js answers

by Danny
Published 2 min read

Next.js has four main ways to redirect: redirect() and permanentRedirect() in your code, redirects in next.config, and proxy.ts. Here is which one to reach for and why.

The short answer

#

Inside a Server Component, Server Action or Route Handler, call redirect() from next/navigation. For fixed URL changes that never depend on data, such as an old blog path, add a rule to redirects in next.config.ts. For checks that must run before any page renders, such as a signed-in cookie, use proxy.ts.


_10
import { redirect } from 'next/navigation';
_10
_10
export default async function Page() {
_10
const user = await getUser();
_10
if (!user) redirect('/login');
_10
_10
return <h1>Welcome back, {user.name}</h1>;
_10
}

Why it happens

#

There is no single redirect API because redirects happen at different moments in a request.

  • next.config redirects are checked first, before the request reaches your app. They suit permanent moves.
  • proxy.ts (called middleware.ts before Next.js 16) runs next, for every matching request, and can read cookies and headers.
  • redirect() and permanentRedirect() run while a route is rendering or while a Server Action or Route Handler runs, so they can use data you have just loaded.
  • useRouter runs in the browser, after the page has loaded, in response to user events.

Picking the earliest stage that has the information you need keeps redirects fast.

How to fix it

#

redirect() and permanentRedirect() in your code

redirect() sends a 307 temporary redirect. permanentRedirect() sends a 308, which tells search engines the move is permanent. Use it when a slug changes.


_12
// app/blog/[slug]/page.tsx
_12
import { notFound, permanentRedirect } from 'next/navigation';
_12
_12
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
_12
const { slug } = await params;
_12
const post = await getPostBySlugOrAlias(slug);
_12
_12
if (!post) notFound();
_12
if (post.slug !== slug) permanentRedirect(`/blog/${post.slug}`);
_12
_12
return <article>{post.title}</article>;
_12
}

In a Server Action, redirect() sends the user on after a form submits. With JavaScript running it does a client-side navigation; for a plain form post it sends a 303 so the browser follows with a GET.


_10
'use server';
_10
_10
import { redirect } from 'next/navigation';
_10
_10
export async function createPost(formData: FormData) {
_10
const post = await db.post.create({ data: { title: String(formData.get('title')) } });
_10
redirect(`/blog/${post.slug}`);
_10
}

Fixed rules in next.config

For URL changes known ahead of time, add them to next.config.ts. permanent: true sends a 308 and permanent: false sends a 307. Path parameters such as :slug carry over.


_13
// next.config.ts
_13
import type { NextConfig } from 'next';
_13
_13
const nextConfig: NextConfig = {
_13
async redirects() {
_13
return [
_13
{ source: '/old-blog/:slug', destination: '/blog/:slug', permanent: true },
_13
{ source: '/docs', destination: '/guides', permanent: false },
_13
];
_13
},
_13
};
_13
_13
export default nextConfig;

Request checks in proxy.ts

When the decision depends on the request but not on page data, redirect in proxy.ts at the project root. Use matcher so it only runs where needed.


_12
// proxy.ts
_12
import { NextResponse, type NextRequest } from 'next/server';
_12
_12
export function proxy(request: NextRequest) {
_12
if (!request.cookies.has('session')) {
_12
return NextResponse.redirect(new URL('/login', request.url));
_12
}
_12
}
_12
_12
export const config = {
_12
matcher: ['/dashboard/:path*'],
_12
};

A cookie check here is an early, optimistic check. Still verify the session where you read the data.

Redirect after a click

redirect() cannot be called from an event handler. In a Client Component, use the router instead.


_10
'use client';
_10
_10
import { useRouter } from 'next/navigation';
_10
_10
export function DoneButton() {
_10
const router = useRouter();
_10
return <button onClick={() => router.push('/dashboard')}>Done</button>;
_10
}

Common pitfalls

#
  • Calling redirect inside try. redirect() works by throwing a special error. If you catch it, the redirect never happens. Call it after the try block.
  • Writing return redirect(). You do not need return; the function never returns. TypeScript knows this because its return type is never.
  • Importing from next/router. That is the Pages Router. In the App Router use next/navigation.
  • Using permanent redirects for temporary moves. Browsers cache 308s hard. Use 307 while you are unsure.
  • Redirect loops. A proxy that sends everyone without a cookie to /login must not match /login itself. Check your matcher.
  • Still using middleware.ts. In Next.js 16 the file and exported function are named proxy. The old name is deprecated.
#

Was this resource helpful?