From 2c22be24cc318915facf286b539ce63018349070 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 14 Nov 2020 17:46:42 -0600 Subject: [PATCH] Add Define URL Redirects In The Next Config as a Next.js til --- README.md | 7 +++- ...define-url-redirects-in-the-next-config.md | 37 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 nextjs/define-url-redirects-in-the-next-config.md diff --git a/README.md b/README.md index d1bbf27..759fbdc 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_959 TILs and counting..._ +_960 TILs and counting..._ --- @@ -32,6 +32,7 @@ _959 TILs and counting..._ * [Mac](#mac) * [MongoDB](#mongodb) * [MySQL](#mysql) +* [Next.js](#next-js) * [Phoenix](#phoenix) * [PostgreSQL](#postgresql) * [Python](#python) @@ -423,6 +424,10 @@ _959 TILs and counting..._ - [Show Tables That Match A Pattern](mysql/show-tables-that-match-a-pattern.md) - [Show Indexes For A Table](mysql/show-indexes-for-a-table.md) +### Next.js + +- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md) + ### Phoenix - [Bypass Template Rendering](phoenix/bypass-template-rendering.md) diff --git a/nextjs/define-url-redirects-in-the-next-config.md b/nextjs/define-url-redirects-in-the-next-config.md new file mode 100644 index 0000000..d69d223 --- /dev/null +++ b/nextjs/define-url-redirects-in-the-next-config.md @@ -0,0 +1,37 @@ +# Define URL Redirects In The Next Config + +In [Add Web Server Layer Redirects](vercel/add-web-server-layer-redirects.md), +I explained how to define URL redirects to your [Vercel](https://vercel.com/) +configuration for a [Next.js](https://nextjs.org/) app. Because these redirect +rules are defined in `vercel.json` which is processed at the time of deployment +on the Vercel platform, you are unable to experience these redirects with your +local dev instance of the app. That could be misleading and cause confusion +during development. + +Instead, you can define your redirects in `next.config.js` as part of the +Next.js app's configuration. When locally running the Next dev server, these +redirects will be processed and active. + +Here is an example of these redirects in `next.config.js`: + +```javascript +const nextConfig = { + async redirects() { + return [ + { + source: "blog/old-blog-post-name", + destination: "blog/new-blog-post-name", + permanent: true, + }, + { + source: "/store", + destination: "store.example.com" + permanent: true, + }, + ] + }, +} +``` + +These will be 308 Permanent Redirects because of `permanent: true`. You can +change that to `false` to make them into 307s.