'Dynamic redirects with Gatsby
Given a Gatsby application with dynamically generated product urls on build:
- /product/x/
- /product/x/variant1/
- /product/x/variant2/
- /product/y/
- /product/y/variant1/
- ...
Is there a way to automatically cause access to non-existing sub-urls of each product to redirect to the root of that product? Preferably on the server-side (gatsby-ssr.js).
Like this:
- /product/x/variantdoesnotexist/ => /product/x/
- /product/x/* => /product/x/ (When * is not a valid url part)
- /product/y/variantdoesnotexist/ => /product/y/
- ...
Only found a client-side solution so far, which includes checking path in the 404 page template and doing a conditional window.location.assign. This is not very optimal as it flashes the 404 page before redirecting and does not perform a 302/301 redirect.
Solution 1:[1]
You can use createRedirect action in the gatsby-node.js:
exports.createPages = async ({ graphql, actions }) => {
const { createRedirect } = actions;
createRedirect({
fromPath: `/product/*/foo`,
toPath: `/product/*`,
});
}
Tweak it as you wish, you can use your current redirects rules within createRedirect.
Keep in mind that in createPages is where you create all dynamic pages hence you have all the slugs and paths available to make your dynamic redirects.
More details: https://support.gatsbyjs.com/hc/en-us/articles/1500003051241-Working-with-Redirects-and-Rewrites
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ferran Buireu |
