Redirects are an essential part of web development. They let you route incoming request paths to different destination paths (or external links of other websites). Redirects are crucial for maintaining a healthy site structure, especially when URLs change.
Next.js provides a robust mechanism for handling redirects. It offers a high degree of flexibility, allowing developers to manage redirects in various ways. This flexibility is particularly useful when dealing with complex routing requirements.
3 Ways to Redirect in Next.js 14
In Next.js 14, there are three primary methods to implement redirects:
- Using the
next.config.js
file - Using the
redirect()
function - Using the
permanentRedirect()
function
Each approach has its unique characteristics, use cases, and code examples, which we will explore in the following sections.
Redirects Using next.config.js
The next.config.js
file is one way to handle redirects in Next.js. This approach uses the redirects
key, where you can specify an array of objects defining the source
, destination
, and permanent
properties.
module.exports = {
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
}
This code specifies that all requests to the /about
path should be redirected to the /
path. The permanent
property is set to true
, signifying a 308 status code.
Redirects Using redirect() Function
Next.js 14 introduces the redirect()
function, which offers a flexible, streamlined way to manage redirects. This function can be used within Server Components, Client Components, Route Handlers, and Server Actions.
Hereโs a code snippet demonstrating its usage:
import { redirect } from 'next/navigation'
export default function Profile({ params }) {
const user = fetchUser(params.id)
if (!user) {
redirect('/login')
}
// ...
}
In this code, the redirect()
function is used to redirect unauthenticated users to the login page.
Redirects Using permanentRedirect() Function
For creating permanent redirects, Next.js offers the permanentRedirect()
function. This function sends a 308 HTTP redirect response (itโs more sophisticated than 301 redirects), indicating that the requested resource has been permanently moved to a new location.
Hereโs how you can use the permanentRedirect()
function:
import { permanentRedirect } from 'next/navigation'
export default function Profile({ params }) {
const user = fetchUser(params.id)
if (!user) {
permanentRedirect('/login')
}
// ...
}
In this example, the permanentRedirect()
function is used to permanently redirect unauthenticated users to the login page.
When to Use Which Redirect in Next.js
When it comes to choosing which redirect method to use in Next.js, it largely depends on your specific needs.
- If you need to manage a large number of redirects across your application, the
next.config.js
file might be the most suitable choice. - If you need to perform redirects based on certain conditions or application state, the
redirect()
function is likely the best option. - If you need to create a permanent redirect, the
permanentRedirect()
function is the way to go.
Redirect Parameters
In Next.js, the redirect methods accept several parameters that dictate their behavior. Some of the key parameters include source
, destination
, permanent
, basePath
, and locale
. Each of these parameters has its unique role and understanding them can help you leverage redirects more effectively.
Source
The source
is the incoming request path pattern. This is essentially the URL that you want to redirect from.
Destination
Destination
is the path you want to direct the incoming request to. This is the URL that you want to redirect to.
Permanent
The permanent
property determines whether the redirect is temporary or permanent. If permanent
is true, it means the redirect is permanent and should be cached by clients or search engines. If permanent
is false, it means the redirect is temporary and should not be cached.
BasePath
When using basePath
support with redirects, the source and destination paths are automatically prefixed with the basePath
. If you want to exclude the basePath
, you can add basePath: false
to the redirect.
Locale
When leveraging i18n
support with redirects, the source and destination paths are automatically prefixed to handle the configured locales. If you want to exclude the locale, you can add locale: false
to the redirect.
Next.js and HTTP Status Codes
In Next.js, the permanent
property in redirects also determines the HTTP status code used. If permanent
is true, a 308 status code is used. A 308 status code is a permanent redirect that instructs clients or search engines to cache the redirect forever.
On the other hand, if permanent
is false, a 307 status code is used. A 307 status code is a temporary redirect and is not cached. This status code is useful when the redirect is not expected to last for long.
Understanding these status codes is crucial as they tell search engines how to handle the redirect properly, which can make your site reach a larger audience.
Redirects with basePath Support
When using basePath
support with redirects in Next.js, the source and destination paths automatically include the basePath
. This means that if your application has a basePath
of /docs
, a source path of /about
will become /docs/about
, and a destination path of /
will become /docs/
.
Here is an example:
module.exports = {
basePath: '/docs',
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
}
However, if you want to exclude the basePath
, you can add basePath: false
to the redirect.
module.exports = {
basePath: '/docs',
async redirects() {
return [
{
source: '/about',
destination: 'https://example.com',
basePath: false,
permanent: true,
},
]
},
}
Redirects with i18n Support
In the context of internationalization (i18n), Next.js automatically prefixes each source and destination to handle the configured locales. This means that if your application supports English (โenโ), French (โfrโ), and German (โdeโ) locales, a source path of โ/aboutโ will be handled for all these locales.
Here is an example:
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
}
On the other hand, if you want to exclude the locale, you can add locale: false
to the redirect.
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async redirects() {
return [
{
source: '/en/about',
destination: '/en/',
locale: false,
permanent: true,
},
]
},
}
Conclusion
Redirects are an indispensable tool in any web developerโs toolkit, and Next.js provides various ways to implement them. Whether youโre looking to manage a large number of redirects across your application or need to perform redirects based on application state, Next.js has you covered. Understanding how to leverage these redirect methods can significantly enhance your Next.js development experience.