3

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? :)

Felipe César
  • 1,234
  • 2
  • 16
  • 34
  • Did you find any solution for this? – Simon Sep 12 '20 at 15:12
  • not yet Simon. I'm using a plugin called `gatsby-plugin-create-client-paths`. It works well for custom prefixed routes like `/app` but I wasn't able to make it work on the root route `/` – Felipe César Sep 14 '20 at 03:35

1 Answers1

3

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.

INT
  • 910
  • 4
  • 21
  • 45
  • Not sure if Filipe has seen this answer, but it worked for me. I was also using the same plugin. – RebeloX Oct 16 '21 at 12:13