Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 367
Daksh Avatar asked Feb 25 '19 16:02

Daksh


1 Answers

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.

like image 151
Derek Nguyen Avatar answered Sep 28 '22 09:09

Derek Nguyen