0
0
GraphQLquery~5 mins

Persisted queries in GraphQL

Choose your learning style9 modes available
Introduction

Persisted queries help make GraphQL requests faster and safer by storing queries on the server. This way, clients only send a small ID instead of the full query text.

When you want to reduce the amount of data sent over the network for repeated queries.
When you want to improve security by allowing only predefined queries to run.
When you want to speed up query execution by caching query plans on the server.
When building mobile apps with limited bandwidth to save data usage.
When you want to simplify client code by referencing queries by ID.
Syntax
GraphQL
1. Store your GraphQL query on the server and assign it a unique ID.
2. Client sends a request with the query ID instead of the full query.
3. Server looks up the query by ID and executes it.

The exact method to store and retrieve persisted queries depends on your GraphQL server setup.

Clients must know the query IDs beforehand to use persisted queries.

Examples
This is the original GraphQL query saved on the server with a unique ID.
GraphQL
# Example of a stored query on the server:
query GetUser {
  user(id: "123") {
    name
    email
  }
}

# This query is saved with ID: "getUser123"
The client sends just the ID instead of the full query text.
GraphQL
# Client sends only the ID:
{
  "id": "getUser123"
}
The server uses the ID to find and execute the stored query.
GraphQL
# Server receives the ID, finds the query, and runs it.
# Server returns the user data as usual.
Sample Program

This example shows how a client sends a query ID, the server looks up the full query, runs it, and returns the data.

GraphQL
# Simulated example using a JSON request for a persisted query
# Client request:
{
  "id": "getUser123"
}

# Server stored queries:
{
  "getUser123": "query GetUser { user(id: \"123\") { name email } }"
}

# Server executes the stored query and returns:
{
  "data": {
    "user": {
      "name": "Alice",
      "email": "alice@example.com"
    }
  }
}
OutputSuccess
Important Notes

Persisted queries reduce bandwidth by sending only IDs instead of full queries.

They improve security by limiting which queries can run on the server.

Make sure to handle errors when an unknown query ID is sent.

Summary

Persisted queries store GraphQL queries on the server with unique IDs.

Clients send only the ID to run a query, saving data and improving speed.

This technique also helps secure your API by controlling allowed queries.