How to redirect from the index page to a route which is generated programmatically, in a Gatsby.JS project

From @reach/router docs:

Redirect works with componentDidCatch to prevent the tree from rendering and starts over with a new location.

Because React doesn’t swallow the error this might bother you. For example, a redirect will trigger Create React App’s error overlay. In production, everything is fine. If it bothers you, add noThrow and Redirect will do redirect without using componentDidCatch.

Add a noThrow tag seems to solve this:

<Redirect noThrow to="/topath" />

You could also ask Gatsby to do this for you, in gatsby-node.js:

exports.createPages = ({ actions }) => {
  const { createRedirect } = actions

  createRedirect({
    fromPath: `/`,
    toPath: `/topath`,
    redirectInBrowser: true,
    isPermanent: true,
  })
}

See more here.


I'd add this redirect rule to where the site is hosted as well.


Use this instead. The useEffect is the React hook equivalent to componentDidMount.

import { useEffect } from 'react';
import { navigate } from 'gatsby';

export default () => {
  useEffect(() => {
    navigate('/blog/');
  }, []);
  return null;
};