Search code examples
routesgatsbyclient-side

Do Gatsby client-side routes require square brackets?


I'm adding client-side routes to an existing website. I'm about to wrap up the project and I noticed the Gatsby docs say you need to put client-side routes in files/folders with square brackets around their names (eg: parentpath/[somepathprop].js). I haven't used that format in any of my client-side routing files, but everything works. Why does Gatsby recommend the square brackets?

I am using the gatsby-plugin-create-client-paths plugin.

What's the issue with a pages/users/index.js file like this? enter image description here


Solution

  • Gatsby recommends using the bracket notation ([]) for those cases where there is some unknown parameter for Gatsby at the build time, like identifiers that are part of a page slug (/user/:id), as your case seem to be, to avoid code-breaking or wrong redirections for an unknown field. For example: src/pages/users/[id].js will generate a route like /users/:id.

    In your case, since you are using gatsby-plugin-create-client-paths plugin you are allowing Gatsby to generate pages under /user path, which only exists in the client.

    What's the issue with a pages/users/index.js file like this?

    As I said, in your use case your approach may work, but keep in mind that if you need to generate a path like /user/123456789, the project may break since it's an unknown route in the system. That's why the square notation helps you in this case.

    Said that, test carefully your project in both gatsby develop and gatsby build to be sure that everything works as expected.

    Do Gatsby client-side routes require square brackets?

    It depends on each case but ideally, yes. The main goal of using this notation is to avoid wrong behaviors (wrong redirections or potential compilation issues) for unknown fields, especially when they are part of the URL.