reactjsgatsby

How add ability add query params for gatsby routes?


How to generate pages in gatsby that will allow you to add parameters to the routing like https://page1?someParam=param or https://page1/param

What I mean? When we navigate to page page1 in gatsby it work's fine, but what if I just want add uniq params for page for Google Analytics? So for this I want to have ability, add some additional params for the page from where I made redirect, but when I add for page1 some params like https://page1?someParam=param or https://page1/param, it updated and show me just https://page1 instead.

I suppose that it's related to way how I created pages. Here is my code:

  createPage({
  path: `${localePrefix}/${slug}`, // so should I change it here in order to work as needed?
  component: PageTemplate,
  context: {
    ...context,
    localizedPaths,
  },
})

Can it be fixed with?
matchPath: path: ${localePrefix}/${slug}?*,
matchPath: path: ${localePrefix}/${slug}/*,

Recap: my question is about why gatsby remove query params from pages?

https://some_site/some_page?some_param=323

translates into

https://some_site/some_page

Solution

  • https://page1?someParam=param or https://page1/param are not the same. While a query parameter (first case: ?someParam=param) is an optional value that doesn't change the rendered page (it doesn't point to any specific route hence it's not requesting any file). The second one (https://page1/param) is accessing a /pages/param route.

    Since they are URL parameters, you don't need to change anything in your project, you just need to catch them using JavaScript. They are handled in thee:

    const urlParams = new URLSearchParams(window?.location?.search); 
    

    Note: you can access directly location prop in Gatsby

    If your project is replacing https://some_site/some_page?some_param=323 to https://some_site/some_page it's because some server-side configuration or a CDN, not because of Gatsby's behavior, like any other React project.