In this article, we describe the following methods to redirect a path to another location by using Next.js and Vercel features:
Using Edge Middleware, 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 1024 redirects
set in your next.config.js
file or vercel.json
.
With Edge Middleware
At the moment, there is a limit of 1024 redirect rules that can be described in the configuration for Vercel deployed apps. To effectively bypass the limit 1024 "Routes created per Deployment" limit, it is advised to migrate your static redirects to Edge Middleware.
1//middleware.ts2import { NextResponse } from 'next/server';3import type { NextRequest } from 'next/server';4
5// config with custom matcher6export const config = {7 matcher: '/about/:path*',8};9
10export default function middleware(request: NextRequest) {11 return NextResponse.redirect(new URL('/about-2', request.url));12}13
Edge Middleware can also be paired with Edge Config where a JSON blob of redirect rules can be stored and read from.
1//middleware.js2import { get } from '@vercel/edge-config';3import { NextResponse } from 'next/server';4
5export const config = {6 matcher: '/((?!api|_next/static|favicon.ico).*)',7};8
9export default async function middleware(request) {10 const url = request.nextUrl;11 const redirects = await get('redirects');12
13 for (const redirect of redirects) {14 if (redirect.source === url.pathname) {15 url.pathname = redirect.destination;16 return NextResponse.redirect(url);17 }18 }19
20 return NextResponse.next();21}
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.
1// next.config.js2module.exports = {3 async redirects() {4 return [5 {6 source: "/legacy/:path*",7 destination: "/new/:path"8 }9 ]10 }11}
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.
1// pages/redirects.js2import Error from 'next/error'3
4export async function getServerSideProps({req, res}) {5 // Insert redirect rules here6 if (req.url.startsWith('/example')) {7 res.statusCode = 3088 res.setHeader('location', '/test')9 // Caching headers10 res.setHeader('Cache-control', 's-maxage=600')11 return res.end()12 }13 14 return { props: { errorCode: 404 } }15}16
17export default function Page({ errorCode }) {18 return <div>`${errorCode}`</div>19}
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.
1// next.config.js2module.exports = {3 async rewrites() {4 return [5 {6 source: "/ad-campaign/:path*",7 destination: "/redirects"8 }9 ]10 }11}
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.
1// pages/api/redirects.js2export default (req, res) => {3 // Insert redirect rules here4 if (req.url.startsWith('/example')) {5 res.statusCode = 3086 res.setHeader('location', '/test')7 // Caching headers8 res.set('Cache-control', 's-maxage=600')9 return res.end()10 }11
12 res.statusCode = 40413 return res.end('Not found')14}
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.
1// next.config.js2module.exports = {3 async rewrites() {4 return [5 {6 source: "/ad-campaign/:path*",7 destination: "/redirects"8 }9 ]10 }11}
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.
1{2 "redirects": [3 {4 "source": "/legacy/:path*",5 "destination": "/new/:path*"6 }7 ]8}
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.
1// api/redirects.js2module.exports = async (req, res) => {3 // Insert redirect rules here4 if (req.url.startsWith('/example')) {5 res.statusCode = 3086 res.setHeader('location', '/test')7 // Caching headers8 res.set('Cache-control', 's-maxage=600')9 return res.end()10 }11
12 res.statusCode = 40413 return res.end('Not found')14}
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.
1{2 "rewrites": [3 { "source": "/ad-campaign/:match*", "destination": "/api/redirects" }4 ]5}6
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.