How to Get Query String Parameter Values in Gatsby

Christopher Fitkin
2 min readApr 18, 2019

--

In this article you will learn how to read the query string parameters in a URL in Gatsby to display dynamic content at runtime.

https://www.myurl.com/?variable=value ←this part

To do this we leverage the functionality of Reach Router, the underlying router packaged in Gatsby, and wrap that functionality in a higher order component (HOC).

WARNING: Using this method will only affect the client-side rendering of your components, not the static server-side rendered html.

This article assumes that you already have a Gatsby site and are familiar with JavaScript and HTML. If you don’t, you can create a starter site using the Gatsby CLI tool: https://www.gatsbyjs.org/docs/starters/

Step 1: Install node packages

@reach/router is installed by default as a Gatsby dependency, this adds it to your package.json file for IDE and linting analysis. We use the query-string package to parse the raw value from Reach Router.

Step 2: Create a Higher Order Component (HOC) that reads the location.search property from Reach Router’s Location provider and passes its child component.

Step 3: Wrap your dynamic component using withLocation and access the search prop provided by the HOC.

Step 4: Embed your custom component and watch the output change based on the query string in your URL.

<CustomQueryStringComponent />

--

--

Christopher Fitkin

Web developer passionate about technology, outdoors, and beer.