Skip to main content

Client Data Fetching


This article touches on how to fetch data at both build time and run time. It uses the plugin gatsby-source-graphql to fetch data at build time on the server, while it uses the axios package to fetch different data on the client-side when the page loads.

When this article mentions hydration, it means that Gatsby (through React.js) builds static files to render server-side. When Gatsby’s script bundle downloads and executes in the browser, it preserves the HTML markup built by Gatsby and turns the site into a full React web application that can manipulate the DOM. The result of this process creates fast loading pages and a nice user experience.

Compiling pages at build-time is useful when your website content won’t change often, or when triggering a build process to recompile works fine. However, some websites with more dynamic needs require a client-side runtime to handle constantly changing content after the page loads, like a chat widget or an email client web application.

Combining build-time and client run-time data

Because a Gatsby site hydrates into a React app after loading statically, Gatsby is not just for static sites. You can also fetch data dynamically on the client-side as needed, like you would with any other React app.

To illustrate this, check out a small example site that uses both Gatsby’s data layer at build-time and data on the client at run-time. This example is based loosely on Jason Lengstorf’s Gatsby with Apollo example. You’ll be fetching character data for Rick (of Rick and Morty) and a random pupper image.

Note: Check out the full example here, if helpful.

1. Create a Gatsby page component

No data yet. Just the basic React page that you’ll be populating.

2. Query for character info at build time

To query for Rick’s character info and image, you’ll use the gatsby-source-graphql plugin. This will allow you to query the Rick and Morty API using Gatsby queries.

Note: To learn more about using gatsby-source-graphql, or about Gatsby’s GraphQL data layer, check out their respective docs. The purpose of including it here is only for comparison.

Now you can add the query to your index.js page:

3. Fetch pupper info and image data on the client

Now you’ll finish out by fetching pupper info from the Dog CEO Dog API. (You’ll fetch a random pupper. Rick isn’t picky.)

That’s it — an example of querying for data at build time using the Gatsby GraphQL data layer and dynamically requesting data on the client at run time.

Other resources

You may be interested to check out other projects (both used in production and proof of concepts) that illustrate this usage:

Edit this page on GitHub