Image

Simplifying GraphQL Queries in Sitecore XM Cloud with TypeScript

Automatically convert .graphql files into usable TypeScript constants for clean, scalable query management.

Author
Robert Watson
July 10, 2025

Intro

Managing GraphQL queries in Sitecore XM Cloud projects can quickly become messy—especially when you’re dealing with dynamic UIs and complex query structures. Embedding raw query strings directly in your code is not only error-prone but also makes refactoring a pain.

In this article, I’ll show you a cleaner way: how to define your queries in .graphql files, automatically convert them into TypeScript constants, and use them directly in your app—making your codebase more modular, readable, and maintainable.

Steps

Step 1: Create your .graphql files

Inside your project, create a queries/ directory and add your .graphql files—each representing a single GraphQL query or fragment. Example:

Step 2: Add the Code Generation script

Next, we actially need to create the code file which will transform the quieries into a text string readable by the typescript interface. Create a TypeScript script like generate-queries.ts to scan the queries/ folder and generate an exportable TypeScript file:

Step 3: Hook up the script to your package.json

Add a custom npm script so you can run this with a single command:

Now, all you need to do is run the following command from your console/terminal and a file named Generated.ts will be created for you

The result should be something like this:

Step 4: Use the Queries in your code

Anywhere in your application, import the generated queries directly:

This keeps your logic and your queries cleanly separated—and plays well with tools like GraphQL Code Generator or typed clients later. You could take it a step further and create yourself a nice helper class to call these queries. For example:

This way, you do not have to worry about getting the graphqlClientFactory from your other code. You keep everything nice and clean!

Final Thoughts

This approach keeps your GraphQL layer organized and scalable, especially as your component library grows. Instead of juggling long query strings in code, you now have modular, readable .graphql files and a predictable way to load them at build time.

In future posts, I’ll share how to integrate this with typed query responses and automated query linting.

Made in React Bricks