Authentication
Attach credentials to every request.
The client's transformRequest returns the request to send instead of the one it built. Use it to add an auth header or send cookies. See Request transforms for reading or replacing the request itself.
Static headers
For a token known at startup:
src/client.ts
import { Client } from "@zoontek/gql-client";
import schemaConfig from "./schemaConfig.json";
export const client = new Client({
url: "https://api.example.com/graphql",
schemaConfig,
transformRequest: (request) => {
request.headers.set("Authorization", `Bearer ${TOKEN}`);
return request;
},
});Per-request headers
The function runs for every request, so it can read the latest token. It can be async:
src/client.ts
export const client = new Client({
url: "https://api.example.com/graphql",
schemaConfig,
transformRequest: async (request) => {
const token = await getAccessToken();
request.headers.set("Authorization", `Bearer ${token}`);
return request;
},
});If the function throws or rejects, the request fails with a ClientError whose reason is "transform".
Cookies
To send cookies to a different origin, return a request with credentials set:
src/client.ts
export const client = new Client({
url: "https://api.example.com/graphql",
schemaConfig,
transformRequest: (request) =>
new Request(request, { credentials: "include" }),
});On logout
Call client.purge() to drop every cached response, so the next user doesn't see the previous user's data. Mounted queries fetch fresh data.