Become A Redirect Master In Nextjs
Good day, here are 3 ways you can redirect web pages to another internal or external web page using Nextjs.
-
Client-side redirect
Useful for quick single web page redirect. This is a quick workaround to solve problems of the page before your boss or customer notice the problem on the page. -
Redirect in Server Components, Route Handlers, and Server Actions
The redirect function allows you to redirect the user to another URL and can be used in Server Components, Route Handlers, and Server Actions. -
Nextjs next.config.js redirect
You can create redirect in the next.config.js file. Use this if you are migrating websites and need to redirect many web pages
Let me share the soucre codes below.
- Client-side redirects
The useRouter hook allows you to programmatically change routes inside Client Components.
Overall, this component immediately redirects the user to "/redirected-page" when it is rendered, but there might be a short delay before the redirect happens. So user will still see the page for a few seconds. This is just a temporay redirect to use in case of emergency 🚑.
- Next.js 14 introduces the redirect() and permanentRedirect() function which can be use in Server Components, Route Handlers, and Server Actions
Both function accepts two arguments:
- path: The URL to redirect to. Can be a internal URL or external URL
- type: 'replace' will replace the page in history, 'push' (default) will add the redirect URL to the browser history
The redirect function return a 307 (Temporary) HTTP redirect when you use it.
The permanentRedirect will serve a 308 (Permanent) HTTP redirect response. So if user clicks on it via Google search, Google will understand(soon) that this page is permantently redirected and will use your new URL in future search results.
- Nextjs next.config.js file redirect
If you have a lot of web pages to redirect, wildcards to redirect or need to redirect to another domain, this is the best solution to create it inside the next.config.js file.
When it comes to choosing which redirect method to use in Next.js, it largely depends on your specific needs. Hope my source code above helps you to become a redirect master in Next.js