GraphQL best practices in Content SDK apps

When using the Content SDK GraphQL API endpoints, we recommend you follow some general best practices.

Additionally, when you consume the GraphQL API from the front end, we recommend you do the following:

  • Separate your queries into .graphql files. Do not mix them with your code.

    • This helps to keep your code organized, and with a tool like graphql-tag/loader you can import the file like it was a JavaScript file.

    • Having queries that can be analyzed statically makes it easier to validate all them at build time, run a security whitelist, and do other common operations.

    • If doing this is not possible, separate your queries into logically named .js or .ts files that contain only queries, such as mycomponent.graphql.ts.

  • Never use dynamic string-concatenated queries (with non-GraphQL variables in the query text). Query variables must always be GraphQL query variables. Otherwise, you defeat whitelisting, static analysis, and performance analysis—overall, it's just a bad idea.

  • Take advantage of query batching:

    • One of the main advantages of GraphQL over REST is that because GraphQL is a protocol, it can do some things REST can't do.

    • Query batching lets you automatically combine multiple queries (made within a short time span) into a single HTTP request.

  • Use tools to make sure your GraphQL queries are valid against the GraphQL schema, such as eslint-plugin-graphql. This provides build-time safety and helps ensure your queries won't break when run.

Many kinds of GraphQL tools require a copy of your GraphQL Schema to execute correctly, such as:

In some cases, you can download a live schema directly from a SitecoreAI instance. However, if there is no live instance, you need a static copy of the schema.

There are two main types of schema input:

  • A JSON-formatted schema. This is the result of an introspection query against the GraphQL API. This is what GraphiQL uses to give documentation in the browser, for example.

  • A schema-definition language schema. This is a text format that defines the schema in a readable format. You can download this by visiting {ENDPOINT_URL}/schema to get the content, then saving it as a .graphql file.

Changes in the SitecoreAI setup (such as changing or adding templates) will cause the GraphQL schema to change. When you use a static schema file, you must keep it up to date to avoid false validations.

Do you have some feedback for us?

If you have suggestions for improving this article,