October 10, 2024
O. Wolfson
Currently Reading: Redirecting
Next.js provides several ways to handle redirects, each suited to different scenarios, whether they occur after an event or mutation, based on a path or condition, or for scaling a large number of redirects. Below is a brief overview of available redirect options in Next.js 14+ using the App Router.
redirect Functiontsximport { redirect } from 'next/navigation';
export async function createPost(id: string) {
// Create post logic
redirect(`/post/${id}`);
}
permanentRedirect Functionredirect, used in Server Components, Server Actions, and Route Handlers.tsximport { permanentRedirect } from 'next/navigation';
export async function updateUsername(username: string) {
// Update username logic
permanentRedirect(`/profile/${username}`);
}
useRouter Hooktsximport { useRouter } from 'next/navigation';
const Page = () => {
const router = useRouter();
return <button onClick={() => router.push('/dashboard')}>Go to Dashboard</button>;
};
next.config.jsjsmodule.exports = {
async redirects() {
return [
{ source: '/old-path', destination: '/new-path', permanent: true },
];
},
};
NextResponse.redirect in Middlewaretsximport { NextResponse } from 'next/server';
export function middleware(req) {
if (!authenticated) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
}
Each method provides different levels of control over redirection, from client-side navigation to server-side responses. For complex applications with many redirects, solutions like Middleware with databases or Bloom filters can be implemented to ensure performance and scalability.