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
.graphqlfiles. Do not mix them with your code.-
This helps to keep your code organized, and with a tool like
graphql-tag/loaderyou 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
.jsor.tsfiles that contain only queries, such asmycomponent.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:
-
eslint-plugin-graphqlto validate queries at build time. -
graphql-toolsto create a disconnected mock GraphQL API. -
ts-graphql-pluginto provide GraphQL code completion in TypeScript.
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}/schemato get the content, then saving it as a.graphqlfile.
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.