In this article, we describe methods to redirect a path to another location by using Next.js and Vercel features. Using Serverless Functions or Next.js pages to respond with a redirect is useful when you have dynamic redirects stored in a data source or if you reached the limit of redirects
set in your next.config.js
file or vercel.json
.
With Next.js
If you are deploying a Next.js application to Vercel, you can define redirects in the following ways:
- Using the
redirects
configuration. - Using a Next.js page.
- Using an API route.
Using redirects
The main characteristic of the redirects
feature is that it is a build-time configuration. Which means it is only possible to generate it once before the application is deployed.
You can check the official Next.js documentation for instructions on how to define the redirects statically. At the moment, there is a limit of 1024 redirect rules that can be described in the configuration for Vercel deployed apps. If your application is near the 1024 limit, it is advised to check the official documentation for Regex Path Matching or alternative ways, as described below.
// next.config.js module.exports = { async redirects() { return [ { source: "/legacy/:path*", destination: "/new/:path" } ] } }
Redirect configuration that redirects /legacy/abc123example
to /new/abc123example
.
Using a Next.js Page
Performing redirects using a Next.js page gives your deployment the ability to fallback to a normal page with a presentable UI in case the redirect is not found. Therefore, using a page for redirects is recommended if you need to dynamically query an external resource to fetch your list of redirects, and those routes will be shared with your users. To avoid executing the Serverless Function for every request to a certain path, it is also recommended to cache the response.
// pages/redirects.js import Error from 'next/error' export async function getServerSideProps({req, res}) { // Insert redirect rules here if (req.url.startsWith('/example')) { res.statusCode = 308 res.setHeader('location', '/test') // Caching headers res.setHeader('Cache-control', 's-maxage=600') return res.end() } return { props: { errorCode: 404 } } } export default function Page({ errorCode }) { return <div>`${errorCode}`</div> }
Using a page to respond with a cacheable 308
redirect to /test
.
Now that we have a page ready to accept requests and redirect given a condition, it is also necessary to route all relevant paths to the page above. In the code snippet below, we will use rewrites
to adjust our routing behavior.
// next.config.js module.exports = { async rewrites() { return [ { source: "/ad-campaign/:path*", destination: "/redirects" } ] } }
Rewriting every path starting with /ad-campaign/
to /redirects
.
Using an API Route
You can also perform redirects using an API Route. This method is recommended if you need to dynamically query an external resource to fetch your list of redirects, and you want an endpoint that can perform those redirects without a presentable page. To avoid invoking the Serverless Function for every request to a certain path, it is also recommended to cache the response.
// pages/api/redirects.js export default (req, res) => { // Insert redirect rules here if (req.url.startsWith('/example')) { res.statusCode = 308 res.setHeader('location', '/test') // Caching headers res.set('Cache-control', 's-maxage=600') return res.end() } res.statusCode = 404 return res.end('Not found') }
An API route that redirects a request programatically.
With the API route ready to accept requests and perform redirects, we need to configure the routing configuration of the Next.js deployment. In the code snippet below, we will use rewrites
to adjust our routing behavior.
// next.config.js module.exports = { async rewrites() { return [ { source: "/ad-campaign/:path*", destination: "/api/redirects" } ] } }
Rewriting every path starting with /ad-campaign/
to /api/redirects
.
With Vercel.json
If you are not using Next.js, you can still define redirects in the following ways:
- Using the
redirects
configuration. - Using a Serverless Function.
Using redirects
with vercel.json
The redirects
feature should be used if you need less than 1024 and you can describe them statically. If your application is near the 1024 limit, it is advised to check the official documentation for Regex Path Matching using a Serverless Function, as described in this article.
{ "redirects": [ { "source": "/legacy/:path*", "destination": "/new/:path*" } ] }
Redirect configuration that redirects /legacy/abc123example
to /new/abc123example
.
Using a Serverless Function
You can perform redirects with a Serverless Function. This method is recommended if you need to dynamically query an external resource to fetch your list of redirects. To avoid invoking the Serverless Function for every request to a certain path, it is also recommended to cache the response.
// api/redirects.js module.exports = async (req, res) => { // Insert redirect rules here if (req.url.startsWith('/example')) { res.statusCode = 308 res.setHeader('location', '/test') // Caching headers res.set('Cache-control', 's-maxage=600') return res.end() } res.statusCode = 404 return res.end('Not found') }
An example of a Node.js Serverless Function to respond with a redirect.
We have created a Node.js Serverless Function that accepts requests and perform redirects programatically. The next step should be to create a new rewrite rule to adjust our routing behavior.
{ "rewrites": [ { "source": "/ad-campaign/:match*", "destination": "/api/redirects" } ] }
Rewriting every path starting with /ad-campaign/
to /api/redirects
.
Conclusion
As outlined in this article, there are multiple ways to perform redirects when deploying an application to Vercel. If you are using Next.js, it is recommended that you use the next.config.js
configuration if you need statically defined rewrites. If you need to query external resources or perform server-side computation, using a Next.js page or an API Route gives you the required flexibility for advanced use-cases.
For other frameworks, you can either define statically your redirects with vercel.json
or use Serverless Functions for advanced requirements.