Search code examples
reactjshttp-redirecturl-rewritinggatsbynetlify

Netlify Redirect or Rewrite for Gatsby Wildcard Path


So I've already implemented a wildcard path on my gatsby-node.js file:

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions
  if (page.path.match(/^\/my-path/)) {
    page.matchPath = "/my-path/*"
    createPage(page)
  }
}

and this works fine when I am running the site locally (in development). i.e., if i provide /my-path/anything123 or /my-path/asdfasdfasdf, both will lead to a rendering of the component I've created in my Gatsby project under pages/my-path.tsx.

Now we come to my problem. When I deploy my site to Netlify, I don't get the same behavior as in development. Can behavior like this be handled with a redirect or rewrite in Netlify? I don't want to lose the content in what comes after /my-path/, as in reality I'm using it to parse an id, i.e. if the URL in the browser is /my-path/123, I want to be able to see that 123 in window.location.href, and parse it with some logic in my-path.tsx.

I hope this is clear. Appreciate anyone who can help or guide me in the right direction!


Solution

  • Of course after writing this all up the answer becomes clear... I tried it, and it works! for the example I was providing, the following redirect would work in your netlify.toml file:

    [[redirects]]
      from = "/my-path/*"
      to = "/my-path"
      status = 200
      force = true
    

    So it essentially has to match 1:1 with the rules you define in gatsby-node.js.