Persisted Queries in GraphQL
Introduction
Persisted Queries are an advanced feature in GraphQL that allow you to store queries on the server, providing a mechanism for clients to reference them by a unique identifier. This technique enhances performance and security by minimizing the amount of data transmitted and ensuring that only validated queries are executed.
What are Persisted Queries?
Persisted Queries are pre-defined GraphQL queries that are saved on the server with an associated identifier. Instead of sending the entire query with each request, clients can simply send the identifier, significantly reducing the payload size.
How They Work
The workflow of persisted queries generally follows these steps:
- Client sends a query to the server.
- Server stores the query with a unique identifier.
- Client sends subsequent requests using the identifier instead of the full query.
- Server executes the query associated with the identifier and returns the response.
graph TD;
A[Client sends query] --> B[Server stores query];
B --> C[Client requests using identifier];
C --> D[Server executes query];
D --> E[Response sent back];
Implementation
Here’s a basic example of how to implement persisted queries:
Server-side Implementation
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = {
hello: () => 'Hello world!'
};
const persistedQueries = {
'1': 'query { hello }'
};
const app = express();
app.use('/graphql', graphqlHTTP((req, res) => {
const queryId = req.body.queryId;
const query = persistedQueries[queryId];
return {
schema: schema,
rootValue: root,
graphiql: true,
context: { query }
};
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
Client-side Implementation
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ queryId: '1' })
})
.then(response => response.json())
.then(data => console.log(data));
Best Practices
- Always validate queries before persisting them.
- Use a consistent naming convention for identifiers.
- Implement caching mechanisms for frequently used queries.
- Monitor and log query usage for optimization.
FAQ
What happens if a client requests an unknown query ID?
The server should respond with an error message indicating that the query ID is invalid or not found.
Can persisted queries be modified once stored?
Once a query is persisted, it should not be modified. If changes are necessary, the old query should be removed, and a new one should be added with a different ID.
Is it possible to use persisted queries with subscriptions?
Persisted queries are primarily designed for queries and mutations. Subscriptions typically require a different approach due to their real-time nature.