PERFORMANCE

Real World Performance: lazy loading, optimizing media, faster analytics join us Wednesday

ContactSign Up

Gatsby 5, TypeScript, and Generated GraphQL Types: A Walkthrough

Kassian Wren
January 23rd, 2023

Gatsby and TypeScript make a really great pair, with both bringing great features to your tech stack. One of Gatsby’s best features is its GraphQL data layer, and because the GraphQL data is typed, TypeScript’s type checking can make applications much less prone to runtime issues and works well with it. Gatsby brings automatic type generation to the table– Gatsby can create types for your named GraphQL queries. Let’s take a look at how to enable and use this feature.

Example: GitHub Stargazers

You can see a completed sample application on GitHub.

What you’ll build is an app that gets the name and number of Stargazers on the most-starred repositories for the gatsbyjs GitHub account. You’ll store this information in Gatsby’s GraphQL data layer, query it on our index page, and let Gatsby automatically generate the types for the GraphQL query results.

Prerequisites

You should have Node.JS and npm installed on your machine, and run the following:

You’ll need to answer a few questions:

  • What you’d like to name your site, and the folder it’ll be contained in; use whatever you like
  • If you would like to use JavaScript or TypeScript; select TypeScript
  • If you’d like to use a CMS, then a Styling system; select ‘No (or I’ll add it later)’ for both

Finally, you’ll be asked if you want to generate the project. Type ‘y’ and hit Enter. The gatsby-cli tool will handle configuring and installing dependencies for our new project. Once that’s complete, navigate into the new project folder using the name you used when creating the project. I’ll be using VSCode and opening the project folder.

Configuring Type Generation

Now that you’ve got a basic project, we’ll go into gatsby-config.ts and, on line 11 (at the time of this writing) should be an object property called graphqlTypegen, set to true. This is the default from the starter: this can be set to a configuration object for advanced use cases.

Next we’ll get connected to our data source, the GitHub GraphQL API

Querying the GitHub GraphQL API

First, create a personal access token using these instructions. You don’t need to add any permissions, as this token will only be used to read public data. Name it something memorable and set an expiration date.

Copy the token before leaving the page, as if it refreshes, the token cannot be seen again. Create a file inside your project called .env. Copy the code into .env, then replace the right side with your GitHub Personal Access Token. Be sure not to commit this file to source control, where it could end up somewhere public like GitHub!

Next, alter the file at src/pages/index.tsx so that it looks like this:

Next, you’ll install graphql-request to make your request to the GitHub GraphQL API. In your terminal, run:

Open the file in the root of your project called gatsby-config.ts; you want to load the dotenv module and run its config() function to load our GitHub Personal Access Token.

After that, create a file at the root of your project called gatsby-node.ts. In it. you want to load in our graphql-request module. You also want to load the GatsbyNode type from Gatsby. Add the following code to the top of the file:

Then, using the GitHub GraphQL API URL and your Personal Access Token pulled from the .env file, you’ll construct a GraphQLClient, which will allow you to make requests to the API.

You’ll need a type and an interface for our GitHub API data; Gatsby’s typegen extends to its own data layer, not external sources. In your gatsby-node.ts file:

Next there’s a GraphQL query for the GitHub API that will retrieve the top 25 starred repositories under the gatsbyjs account. You’ll store it in a variable for querying:

You need to export a sourceNodes() function in order to create nodes in the Gatsby Data Layer. You’ll make a query request to the GitHub GraphQL API for the data, then log it to the console:

If you run the Gatsby develop script in your terminal:

You should see a long object log in your console while it builds:

Creating Source Nodes in Gatsby’s Data Layer

Now that we’ve got data, let’s create some source nodes in gatsby-node.ts; replace the console.log() statement with the following:

Querying the Data Layer on our Index page

First, add an import for the graphql tag function to the top of src/pages/index.tsx:

You have the data in the GraphQL data layer, and the types will be generated as soon as you add a query to the bottom of src/pages/index.tsx:

Save the file and run npm run develop again, and at the end of the output you should see a line about generating types:

Now you’re ready to use the query data. 

Using the Generated Types

Modify the IndexPage function in src/pages/index.tsx to look like the following:

You can see the Queries global is available to you, and it has the types that were generated for you to use. When you go to localhost:8000, you should now see a list of repository names and stargazer counts:

And that’s it! You’ve now built a TypeScript Gatsby app with auto-generated types for the GraphQL data layer. 

Benefits of TypeScript with Gatsby

As mentioned in the beginning, there are quite a few reasons to use TypeScript with Gatsby. One of the most immediate benefits is type safety for your GraphQL queries with auto-generated types, but this benefit can also spread to all parts of your application. 

You can also get auto suggestions for GraphQL queries into the Gatsby data layer using a plugin and the typegen system. This allows you to prototype and build faster by letting you see the GraphQL schema in the code editor instead of having to switch contexts.

Thanks for reading! If you’re interested in learning more about TypeScript with Gatsby, you can check out the docs. We also have docs on Typegen specifically, as well as an explainer post on the blog.

Share on TwitterShare on LinkedInShare on FacebookShare via Email

Talk to our team of Gatsby Experts to supercharge your website performance.

Contact Gatsby Now
© 2023 Gatsby, Inc.