The GraphQLClient class provides a stateful client for GraphQL requests with persistent configuration, headers, middleware support, and advanced request management. Ideal for applications requiring consistent GraphQL endpoint interaction with shared configuration.
Creates a new GraphQL client instance with endpoint URL and optional configuration.
/**
* GraphQL Client for stateful request management
* @param url - GraphQL endpoint URL
* @param requestConfig - Optional client configuration
*/
class GraphQLClient {
constructor(url: string, requestConfig?: RequestConfig);
}
interface RequestConfig extends Omit<RequestInit, "headers" | "method"> {
fetch?: Fetch;
method?: HTTPMethodInput;
headers?: HeadersInit | (() => HeadersInit);
requestMiddleware?: RequestMiddleware;
responseMiddleware?: ResponseMiddleware;
jsonSerializer?: JsonSerializer;
excludeOperationName?: boolean;
errorPolicy?: ErrorPolicy;
}Usage Examples:
import { GraphQLClient, gql } from "graphql-request";
// Basic client
const client = new GraphQLClient("https://api.example.com/graphql");
// Client with authentication
const authenticatedClient = new GraphQLClient("https://api.example.com/graphql", {
headers: {
authorization: "Bearer your-token-here",
},
});
// Client with full configuration
const advancedClient = new GraphQLClient("https://api.example.com/graphql", {
method: "POST",
headers: {
"user-agent": "MyApp/1.0",
"x-api-key": "api-key",
},
errorPolicy: "all",
excludeOperationName: true,
});Sends GraphQL documents and returns only the data portion of the response.
/**
* Send a GraphQL document
* @param document - GraphQL document to execute
* @param variables - Optional variables for the query
* @param requestHeaders - Optional headers for this request
* @returns Promise resolving to the response data
*/
request<T, V extends Variables = Variables>(
document: RequestDocument | TypedDocumentNode<T, V>,
variables?: V,
requestHeaders?: HeadersInit
): Promise<T>;
/**
* Send a GraphQL document using options object
* @param options - Request options
* @returns Promise resolving to the response data
*/
request<T, V extends Variables = Variables>(
options: RequestOptions<V, T>
): Promise<T>;Usage Examples:
import { GraphQLClient, gql } from "graphql-request";
const client = new GraphQLClient("https://api.example.com/graphql");
const query = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
// Basic request
const user = await client.request(query, { id: "123" });
// Request with additional headers
const userWithHeaders = await client.request(
query,
{ id: "123" },
{ "x-request-id": "req-456" }
);
// Using options object
const userWithOptions = await client.request({
document: query,
variables: { id: "123" },
requestHeaders: { "x-trace-id": "trace-789" },
});Sends GraphQL requests and returns the complete response including errors, extensions, and headers.
/**
* Send a GraphQL query and receive raw response
* @param query - GraphQL query string
* @param variables - Optional variables for the query
* @param requestHeaders - Optional headers for this request
* @returns Promise resolving to complete response with metadata
*/
rawRequest<T, V extends Variables = Variables>(
query: string,
variables?: V,
requestHeaders?: HeadersInit
): Promise<GraphQLClientResponse<T>>;
/**
* Send a raw GraphQL request using options object
* @param options - Raw request options
* @returns Promise resolving to complete response with metadata
*/
rawRequest<T, V extends Variables = Variables>(
options: RawRequestOptions<V>
): Promise<GraphQLClientResponse<T>>;
interface GraphQLClientResponse<Data> {
status: number;
headers: Headers;
data: Data;
extensions?: unknown;
errors?: GraphQLError[];
}Sends multiple GraphQL documents in a single HTTP request for improved performance and atomicity.
/**
* Send multiple GraphQL documents in batch
* @param documents - Array of documents to send
* @param requestHeaders - Optional headers for the batch request
* @returns Promise resolving to array of results
*/
batchRequests<BatchResult extends [Result, ...Result[]], V extends Variables = Variables>(
documents: BatchRequestDocument<V>[],
requestHeaders?: HeadersInit
): Promise<BatchResult>;
/**
* Send batch requests using options object
* @param options - Batch request options
* @returns Promise resolving to array of results
*/
batchRequests<BatchResult extends [Result, ...Result[]], V extends Variables = Variables>(
options: BatchRequestsOptions<V>
): Promise<BatchResult>;
interface BatchRequestDocument<V extends Variables = Variables> {
document: RequestDocument;
variables?: V;
}
interface BatchRequestsOptions<V extends Variables = Variables> {
documents: BatchRequestDocument<V>[];
requestHeaders?: HeadersInit;
signal?: RequestInit["signal"];
}Methods for updating client configuration after instantiation.
/**
* Set multiple headers at once, replacing existing headers
* @param headers - Headers to set
* @returns Client instance for chaining
*/
setHeaders(headers: HeadersInit): this;
/**
* Set a single header value
* @param key - Header name
* @param value - Header value
* @returns Client instance for chaining
*/
setHeader(key: string, value: string): this;
/**
* Change the GraphQL endpoint URL
* @param value - New endpoint URL
* @returns Client instance for chaining
*/
setEndpoint(value: string): this;Usage Examples:
import { GraphQLClient } from "graphql-request";
const client = new GraphQLClient("https://api.example.com/graphql");
// Method chaining for configuration
client
.setHeader("authorization", "Bearer new-token")
.setHeader("x-api-version", "2")
.setEndpoint("https://api-v2.example.com/graphql");
// Set multiple headers
client.setHeaders({
authorization: "Bearer token",
"content-type": "application/json",
"x-client-version": "1.0.0",
});
// Dynamic endpoint switching
if (process.env.NODE_ENV === "production") {
client.setEndpoint("https://prod-api.example.com/graphql");
} else {
client.setEndpoint("https://dev-api.example.com/graphql");
}type RequestMiddleware<V extends Variables = Variables> = (
request: RequestInitExtended<V>
) => RequestInitExtended | Promise<RequestInitExtended>;
type ResponseMiddleware = (
response: GraphQLClientResponse<unknown> | ClientError | Error,
request: RequestInitExtended
) => Promise<void> | void;
interface RequestInitExtended<V extends Variables = Variables> extends RequestInit {
url: string;
operationName?: string;
variables?: V;
}Usage Examples:
import { GraphQLClient } from "graphql-request";
// Request middleware for logging
const loggingMiddleware = (request) => {
console.log("GraphQL Request:", request.operationName);
return request;
};
// Response middleware for analytics
const analyticsMiddleware = async (response, request) => {
if (response instanceof Error) {
console.error("GraphQL Error:", response.message);
} else {
console.log("GraphQL Success:", request.operationName);
}
};
const client = new GraphQLClient("https://api.example.com/graphql", {
requestMiddleware: loggingMiddleware,
responseMiddleware: analyticsMiddleware,
});type ErrorPolicy = "none" | "ignore" | "all";Usage Examples:
import { GraphQLClient } from "graphql-request";
// Default behavior: throw on any GraphQL errors
const strictClient = new GraphQLClient("https://api.example.com/graphql", {
errorPolicy: "none", // default
});
// Ignore GraphQL errors, return data if available
const lenientClient = new GraphQLClient("https://api.example.com/graphql", {
errorPolicy: "ignore",
});
// Return both data and errors (requires rawRequest)
const debugClient = new GraphQLClient("https://api.example.com/graphql", {
errorPolicy: "all",
});type Fetch = typeof fetch;
type HTTPMethodInput = "GET" | "POST" | "get" | "post";
interface JsonSerializer {
stringify: (obj: any) => string;
parse: (obj: string) => unknown;
}
interface RequestOptions<V extends Variables = Variables, T = unknown> {
document: RequestDocument | TypedDocumentNode<T, V>;
requestHeaders?: HeadersInit;
signal?: RequestInit["signal"];
variables?: V;
}
interface RawRequestOptions<V extends Variables = Variables> {
query: string;
requestHeaders?: HeadersInit;
signal?: RequestInit["signal"];
variables?: V;
}