How to redirect to external URL - Next.js


In this tutorial, we will going to show how to redirect to external URL using next.js configuration file
Edit next.config.js
In your config file next.config.js under the root directory, define
- source : The source URL that you want to be redirected
- destination : The destination URL that you want your client to be redirected to
- permanent: set it to true if the redirect will be permanent which gives an HTTP code of 308
The configuration that needed to be done is as below:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async redirects() {
return [
{
source: '/page',
destination: 'https://easyapply.vercel.app/',
permanent: true,
},
]
}
}
module.exports = nextConfig
If you do not have a next.config.js under your root directory, go ahead and create it under root folder with name next.config.js and copy the configuration above.
Once done, do not forget to restart the server to take the modifications into effect, otherwise the redirect will not work
Test the configuration
Create page.js under pages folder and insert the following
export default function Page(){
return (<div>Hello</div>)
}
Now, run http://localhost:3000/page and you should be redirected to https://easyapply.vercel.app/ as the screenshot is displaying below
Conclusion
We have seen how to redirect to an external URL using next.js configuration.
You might be interested in basePath and how you can make the redirect with an existing base path, you can check my article here