Next.js Redirections: A Complete Guide to All 5 Redirection Methods with Examples
Next.js provides robust redirection mechanisms that can optimize navigation, improve user experience, and enhance SEO. Let’s dive into the main types of redirection in Next.js and their best use cases.
1. redirect()
Function
The redirect()
function is a straightforward way to handle redirection in server-side actions. You can use this method to redirect users based on logic, such as authentication status. For instance, redirecting an unauthenticated user to the login page is a common use case.
// Redirect unauthenticated user to login page
import { redirect } from 'next/navigation';
export default function MyPage() {
const isAuthenticated = false;
if (!isAuthenticated) {
redirect('/login');
}
return <div>Secure Content</div>;
}
2. permanentRedirect()
Function
permanentRedirect()
is specifically designed for handling 308 status code redirects in Next.js, which signals to clients and search engines that the redirection is permanent. This function helps manage URL changes that should be consistently followed by browsers, making it ideal for content migrations or restructuring.
// Permanent redirect using permanentRedirect
import { permanentRedirect } from 'next/navigation';
export default function OldPage() {
permanentRedirect('/new-url');
return <div>This content has moved.</div>;
}
3. useRouter
Hook
For client-side navigation, the useRouter
hook offers a smooth, SPA-like transition without reloading the page. This hook is ideal for managing user flow within client components.
import { useRouter } from 'next/router';
export default function HomePage() {
const router = useRouter();
const handleRedirect = () => {
router.push('/destination');
};
return <button onClick={handleRedirect}>Go to Destination</button>;
}
4. Configuring Redirection in next.config.js
If you have multiple redirects that are part of site structure rather than component logic, setting them in next.config.js
centralizes your redirection rules. These configuration-based redirects allow you to set up rules globally, making them easy to manage and optimize for performance.
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-path',
destination: '/new-path',
permanent: true,
},
{
source: '/shop',
destination: '/login',
permanent: false,
},
];
},
};
5. Middleware-based Redirects
For more dynamic or complex redirections, such as those involving authentication or personalized rules, using middleware is ideal. Middlewares intercept requests and allow custom logic before a page load. They’re optimal for handling conditional redirects based on request headers, user roles, or other criteria.
Example: Middleware Redirect to Login
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
const url = req.nextUrl.clone();
if (url.pathname.startsWith('/shop')) {
url.pathname = '/login';
return NextResponse.redirect(url);
}
}
With middleware, you can efficiently manage batch redirections and set complex conditions, enhancing your site's flexibility and performance.
Summary
These redirection methods in Next.js allow you to fine-tune how users navigate your application. Leveraging them effectively can boost SEO, ensure security, and create a seamless user experience. By understanding each method’s strengths and intended use cases, you can make strategic choices that optimize both performance and accessibility in your Next.js applications.