How to redirect all routes to gatsby index

Viewed 1450

I'm trying to make a Gatsby project that has only one page to handle all the routes. I have am index page like this:

const App = () => {
  return <Router>
    <Home path="/"/>
    <Login path="/login" />
    <Content path="/content" />
  </Router>
}

on src/pages folder I have only index.js

How can I make this page handle all the routes?

Checking Gatsby docs (https://www.gatsbyjs.com/docs/client-only-routes-and-user-authentication/) I know that I can use the plugin gatsby-plugin-create-client-paths like this:

{
  resolve: `gatsby-plugin-create-client-paths`,
  options: { prefixes: [`/app/*`] },
},

This works well if I make a page called app.js using a react router. So all the routes /app/* goes to this page.

But how can I make this kind of redirect on the root url: /. I want to make that any route /* goes to the index page: index.js

Any suggestions on how to do this? :)

1 Answers

Setup index.js like this:

const IndexPage = () => {
  return (
    <Router>
      <Home path="/"/>
      <Login path="/login" />
      <Content path="/content" />
    </Router>
  )
}

export default IndexPage

and in gatsby-node.js:

exports.onCreatePage = ({ page, actions }) => {
  const { createPage } = actions
  if (page.path === `/`) {
    page.matchPath = `/*`
    createPage(page)
  }
}

Restart gatsby develop and the index page will handle the routes you've setup.

Related