9

I want to reroute the index / to /blog in a gatsby project. The page at /blog route is generated inside gatsby-node.js file.

What I tried is importing Redirect from @reach-router and inside the Index component returning Redirect to='/blog' but this results in Uncaught RedirectRequest error.

The index.js file:

import React from 'react'
import { Redirect } from '@reach/router'


class BlogIndex extends React.Component {
  render() {
    return (
      <Redirect to={`/blog`} />
    )
  }
}

export default BlogIndex

Error

Daksh
  • 1,064
  • 11
  • 22

2 Answers2

15

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.

Community
  • 1
  • 1
Derek Nguyen
  • 11,294
  • 1
  • 40
  • 64
9

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;
};
Charming Robot
  • 2,460
  • 2
  • 17
  • 34