Reputation: 81
I'm trying to do a redirect in next.config.js to an external url.
{
source: '/hello',
destination: 'https://google.com',
permanent: false,
}
But when I visit mywebsite.com/hello redirects to mywebsite.comhttps://google.com instead of https://google.com (not tested in production, just local)
Do you know how can I configure a redirect to an external url?
Thank you
Upvotes: 0
Views: 4874
Reputation: 7849
Assuming you are using Next v11/12 and Webpack 5, using an async redirects()
function that returns an array of redirects inside of next.config.js
is best practice:
// next.config.js (Next 12 / Webpack 5)
module.exports = {
// Redirects
// First example shows wildcard functionality, all `/blog` to `/news`
// Second example mirrors your use case
async redirects() {
return [
{
source: '/blog/:slug*',
destination: '/news/:slug*',
permanent: true,
},
{
source: '/hello',
destination: 'https://google.com',
permanent: false,
}
]
}
}
The older Next v10 with Webpack 4 worked a little differently. I'd typically leverage some Node plugins - next-compose-plugins
and next-images
(this was before next/images
was a thing).
The basic idea is you're setting up a plugin to make Webpack assembly easier, and one of the plugins processes your imagery during build. You add all of the next config options into an object that the withPlugins
wrapper is ready to receive.
// next.config.js (Next 10 / Webpack 4)
const withPlugins = require('next-compose-plugins')
const withImages = require('next-images')
const {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD
} = require('next/constants')
const nextConfig = {
// Set redirects here, objs in arr as needed
async redirects() {
return []
}
}
// This uses phases as outlined here:
// https://github.com/vercel/next.js/tree/canary/examples/with-env-from-next-config-js
module.exports = withPlugins([
// Processes images during build time
[withImages, {
[PHASE_DEVELOPMENT_SERVER]: 'http://localhost:3000',
[PHASE_PRODUCTION_BUILD]: 'https://example.com'
}]
], nextConfig)
Upvotes: 1