Skip to content

Add useGETForHashedQueries for APQ #2333

@chrfritsch

Description

@chrfritsch

The Apollo client has this feature

Using GET requests with APQ on a CDN
A great application for APQ is running Apollo Server behind a CDN. Many CDNs only cache GET requests, but many GraphQL queries are too long to fit comfortably in a cacheable GET request. When the APQ link is created with createPersistedQueryLink({useGETForHashedQueries: true}), Apollo Client automatically sends the short hashed queries as GET requests enabling a CDN to serve those requests. For full-length queries and for all mutations, Apollo Client will continue to use POST requests.

It would be really nice if the gateway could support this also for downstream APQ requests.
Currently we are using this workaround:

const useGETForHashedQueries = function (): GatewayPlugin {
    return {
        onFetch({ url, options, setURL, setOptions }) {
            if (options.method !== 'POST' || !options.body) return;

            let body: Record<string, unknown>;
            try { body = JSON.parse(options.body as string); } catch { return; }

            if (body.query || !(body.extensions as Record<string, unknown>)?.persistedQuery) return;

            const urlObj = new URL(url);
            if (body.operationName) urlObj.searchParams.set('operationName', body.operationName as string);
            if (body.variables && Object.keys(body.variables as object).length > 0) {
                urlObj.searchParams.set('variables', JSON.stringify(body.variables));
            }
            urlObj.searchParams.set('extensions', JSON.stringify(body.extensions));

            setURL(urlObj.toString());
            setOptions({ ...options, method: 'GET', body: undefined });
        },
    };
};



Metadata

Metadata

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions