Dynamic Routing in Gatsby

Animesh Ghosh
2 min readAug 26, 2020

Gatsby is a React-based Open Source Framework for creating static and dynamic websites. Performance, Scalability, Security, Accesibility and SEO are some of the main features of Gatsby. Building websites on Gatsby and then deploying it to Netlify has become easier with Gatsby.

Developing static websites is at the core of Gatsby but it also supports building dynamic websites with React Framework at it’s core. Routing in Gatsby have been the easiest by creating pages and then using them. But what if I need to develop a route which is like

https://domain.com/description/:id

where the id is an unique identifier and for each id the content of the page that loads is different based on the id. Thus to do so we take help of the createPage given by Gatsby.

Developing Dynamic Routes

In this article, for demonstration purposes i have chosen the following scenario. I have certain blog posts where i have a button of Read More. Clicking on Read More, the specific post description page will open.

The folder structure is as follows:
If gatsby-node.js is not present, then you need to create one in the project root folder.

project
|___ src
| |___ components
| | |___ DescriptionComp
| | |___ DescriptionComp.js
| | |___ DescriptionComp.css
| |___ pages
| |___ description.js
|___ gatsby-node.js

Now, in gatsby-node.js add the following configuration.

In the above code, the createPage helps to generate the dynamic pages. The page.path.match() helps to match the route which is https://domain.com/description/* . The createPage then generates the page where path is the page path, matchPath defines the path to be matched with :id as the identifier and component resolves the template which needs to be rendered.

Now in the description.js you can get the identifier as a prop to the component

const Description = ({id}) => {
return <DescriptionComp id={id}></DescriptionComp>
}

In this way you get the unique identifier and based on that you can make axios request for the data and render accordingly.

A small tip while deploying on Netlify

Netlify is just a CDN so by default it does not have any idea about these routes which would cause errors after deploying a website with such dynamic routes. The solution to this is that we specify a _redirects.txt file which should be under static folder.

project
|___ static
|___ _redirects

And add the following code inside it

/description/:id /description 200

You can read more about the _redirects file over here.

Conclusion

Thus using this you would be able to create dynamic routes easily through Gatsby and can easily develop Dynamic websites.

--

--

Animesh Ghosh

Passionate about developing products and delivering great experiences. Currently working as a Project Manager @ Microsoft