Automatic Persisted Queries
Unlike REST APIs that use a fixed URL to load data, GraphQL provides a rich query language that can be used to express the shape of application data requirements. This is a marvelous advancement in technology, but it comes at a cost: GraphQL query strings are often much longer than REST urls — in some cases by many kilobytes.
In practice, we’ve seen GraphQL query sizes ranging well above 10 KB just for the query text. This is significant overhead when compared with a simple URL of 50-100 characters. When paired with the fact that the uplink speed from the client is typically the most bandwidth-constrained part of the chain, large queries can become bottlenecks for client performance.
Automatic Persisted Queries solves this problem by sending a generated ID instead of the query text as the request.
Read more about Automatic Persisted Queries.
How It Works
- When the client makes a query, it will optimistically send a short (64-byte) cryptographic hash instead of the full query text.
- If the backend recognizes the hash, it will retrieve the full text of the query and execute it.
- If the backend doesn’t recognize the hash, it will ask the client to send the hash and the query text to it can store them mapped together for future lookups. During this request, the backend will also fulfill the data request.
Installation
npm i apollo-angular
If you do not already have an SHA-256 based hashing function available in your application, you will need to install one separately. For example:
npm i crypto-hash
This link doesn’t include an SHA-256 hash function by default, to avoid forcing one as a dependency. Developers should pick the most appropriate SHA-256 function (sync or async) for their needs/environment.
Usage
Use createPersistedQueryLink
function and put it before HttpLink
in the link chain.
import { provideApollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { createPersistedQueryLink } from 'apollo-angular/persisted-queries';
import { sha256 } from 'crypto-hash';
import { inject } from '@angular/core';
import { InMemoryCache } from '@apollo/client/core';
provideApollo(() => {
const httpLink = inject(HttpLink);
return {
link: createPersistedQueryLink({ sha256 }).concat(httpLink.create({ uri: '/graphql' })),
cache: new InMemoryCache(),
// other options ...
};
});
That’s it! Now your client will start sending query signatures instead of the full text resulting in improved network performance.
- Check Options
- Read about protocol
- Build time generation
- Learn more about Automatic Persisted Queries
More
This library is just a simple wrapper of
@apollo/client/link/persisted-queries
to make it work in Angular with apollo-angular/http
(also with batch link). Thanks to that you can
use any options, any functionality that the original package provides.