I made a change to the URL of one of my subpages that is already live. The old link is no longer supported, but it is still present in many places. Instead of updating all instances of the old link, I would like to set up a redirect from the old URL to the new one. I came across Next.js Redirects as a possible solution, but I am encountering issues with its implementation.
The original URL was:
http://localhost:3000/product/id
The new URL now looks like this:
http://localhost:3000/product/SLUG-id
My API fetches data based solely on the ID in getServerSideProps. Previously, the slug was separated from the ID.
export const getServerSideProps = async (context: any) => {
const slugId = context.params.slugId;
const id = slugId.split('-').pop();
const apolloClient = initializeApollo(context);
const { data } = await apolloClient.query({
query: GET_PRODUCTS,
variables: {
id,
},
});
return {
props: {
data,
},
};
};
The new flow of the page includes passing the slug when navigating to the product subpage:
<Link href={`/product/${product.slug}-${productId}`}>
The old link contains an ID but lacks a slug component.
When my next config is set as follows, I encounter an error:
module.exports = {
nextConfig,
async redirects() {
return [
{
source: '/product/:slug',
destination: '/product/:slugId',
permanent: true,
},
];
},
};
Editing the next config led to an error:
warn - Invalid next.config.js options detected:
- The root value has an unexpected property, nextConfig, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
See more info here: https://nextjs.org/docs/messages/invalid-next-config
`destination` has segments not in `source` or `has` (slugId) for route {"source":"/product/:slug","destination":"/product/:slugId","permanent":false}
Error: Invalid redirect found
Can I successfully redirect users from the old link to the new one while including the slug in the URL? It seems like getServerSideProps can handle this URL structure and retrieve the necessary data even without the slug in the link, although having the slug included is important for SEO purposes.
Preferred scenario:
User clicks on the old link and is directed to the designated page seamlessly. Data is fetched correctly, and the URL displays the slug-id format, even though only the ID is required for data retrieval.