2020-05-02

Client Side Routing in Gatsby from Root

gatsby, til, selfnote

banner

Image by James Wheeler from Pixabay

Gatsby client-side rendering documentation, Client-only Routes & User Authentication, shows how to implement a client-side routing.

What the issue?

Gatsby works as a SSR, and each route corresponds to a local file.
That means, whenever you use a client-side routing, Gatsby would look for a file (created under either src/pages/* folder or dynamically created within gatsby-node.js), and unfound file would result in 404.

To implement a client-side routing, you need to specify that a certain path is client-side only.

I will use how to configure it with a plugin, gatsby-plugin-create-client-paths_

gatsby-config.js.

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

prefix specifies which sub-route needs to be treated as a client-side routing.
But when you specify /* for the root, you get a 404 response.

Issue persists with manualy configuration in Client-only Routes & User Authentication article

What do you do then?

Nothing. Nada. Nope nothing.

You don't do anything.
Gatsby automatically creates /index.html, so you can simply use @reach/router (underlying router used by Gatsby; No need to install it) to do client-side routing.

You can check out the working sandbox below.

https://codesandbox.io/embed/gatsby-working-root-client-side-routing-43xb1