Skip to main content

TypeScript GraphQL-Request

Usage Requirements

In order to use this GraphQL Codegen plugin, please make sure that you have GraphQL operations (query / mutation / subscription and fragment) set as documents: ... in your codegen.yml.

Without loading your GraphQL operations (query, mutation, subscription and fragment), you won't see any change in the generated output.

Make sure you have typescript plugin and typescript-operations as well in your configuration:

This plugin generates graphql-request ready-to-use SDK, which is fully-typed.


typescript-graphql-request plugin version
Using yarn
yarn add -D @graphql-codegen/typescript-graphql-request

API Reference


type: boolean default: false

By default the request method return the data or errors key from the response. If you need to access the extensions key you can use the rawRequest method.

Usage Examples

- typescript
- typescript-operations
- typescript-graphql-request
rawRequest: true


type: boolean default: false

Deprecated. Changes the documentMode to documentNode.


type: string default: graphql-tag#gql

Customize from which module will gql be imported from. This is useful if you want to use modules other than graphql-tag, e.g. graphql.macro.

Usage Examples

gqlImport: graphql.macro#gql
gqlImport: gatsby#graphql


type: string default: graphql#DocumentNode

Customize from which module will DocumentNode be imported from. This is useful if you want to use modules other than graphql, e.g. @graphql-typed-document-node.


type: boolean default: false

Set this configuration to true if you wish to tell codegen to generate code with no export identifier.


type: boolean default: false

Set this configuration to true if you wish to make sure to remove duplicate operation name suffix.


type: boolean default: false

Set this configuration to true if you wish to disable auto add suffix of operation name, like Query, Mutation, Subscription, Fragment.


type: string default: ``

Adds a suffix to generated operation result type names


type: string default: ``

Changes the GraphQL operations variables prefix.


type: string default: Document

Changes the GraphQL operations variables suffix.


type: string default: ``

Changes the GraphQL fragments variables prefix.


type: string default: FragmentDoc

Changes the GraphQL fragments variables suffix.


type: DocumentMode default: graphQLTag

Declares how DocumentNode are created:

  • graphQLTag: graphql-tag or other modules (check gqlImport) will be used to generate document nodes. If this is used, document nodes are generated on client side i.e. the module used to generate this will be shipped to the client
  • documentNode: document nodes will be generated as objects when we generate the templates.
  • documentNodeImportFragments: Similar to documentNode except it imports external fragments instead of embedding them.
  • external: document nodes are imported from an external file. To be used with importDocumentNodeExternallyFrom

Note that some plugins (like typescript-graphql-request) also supports string for this parameter.


type: boolean default: true

If you are using documentNode: documentMode | documentNodeImportFragments, you can set this to true to apply document optimizations for your GraphQL document. This will remove all "loc" and "description" fields from the compiled document, and will remove all empty arrays (such as directives, arguments and variableDefinitions).


type: string default: ``

This config is used internally by presets, but you can use it manually to tell codegen to prefix all base types that it's using. This is useful if you wish to generate base types from typescript-operations plugin into a different file, and import it from there.


type: string default: ``

This config should be used if documentMode is external. This has 2 usage:

  • any string: This would be the path to import document nodes from. This can be used if we want to manually create the document nodes e.g. Use graphql-tag in a separate file and export the generated document
  • 'near-operation-file': This is a special mode that is intended to be used with near-operation-file preset to import document nodes from those files. If these files are .graphql files, we make use of webpack loader.

Usage Examples

documentMode: external
importDocumentNodeExternallyFrom: path/to/document-node-file
documentMode: external
importDocumentNodeExternallyFrom: near-operation-file


type: boolean default: false

This config adds PURE magic comment to the static variables to enforce treeshaking for your bundler.


type: boolean default: false

If set to true, it will enable support for parsing variables on fragments.


type: boolean default: false

Makes scalars strict.

If scalars are found in the schema that are not defined in scalars an error will be thrown during codegen.

Usage Examples

strictScalars: true


type: string default: any

Allows you to override the type that unknown scalars will have.

Usage Examples

defaultScalarType: unknown


type: ScalarsMap

Extends or overrides the built-in scalars and custom GraphQL scalars to a custom type.


type: NamingConvention default: change-case-all#pascalCase

Allow you to override the naming convention of the output. You can either override all namings, or specify an object with specific custom naming convention per output. The format of the converter must be a valid module#method. Allowed values for specific output are: typeNames, enumValues. You can also use "keep" to keep all GraphQL names as-is. Additionally you can set transformUnderscore to true if you want to override the default behavior, which is to preserves underscores.

Available case functions in change-case-all are camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, lowerCase, localeLowerCase, lowerCaseFirst, spongeCase, titleCase, upperCase, localeUpperCase and upperCaseFirst See more


type: string default: ``

Prefixes all the generated types.

Usage Examples

typesPrefix: I


type: string default: ``

Suffixes all the generated types.

Usage Examples

typesSuffix: I


type: boolean default: false

Does not add __typename to the generated types, unless it was specified in the selection set.

Usage Examples

skipTypename: true


type: boolean default: false

Automatically adds __typename field to the generated types, even when they are not specified in the selection set, and makes it non-optional

Usage Examples

nonOptionalTypename: true


type: boolean default: false

Will use import type {} rather than import {} when importing only types. This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option

Usage Example#

For the given input:

query continents {
continents {
countries {
fragment CountryFields on Country {

It generates SDK you can import and wrap your GraphQLClient instance, and get fully-typed SDK based on your operations:

import { GraphQLClient } from 'graphql-request';
import { getSdk } from './sdk'; // THIS FILE IS THE GENERATED FILE
async function main() {
const client = new GraphQLClient('');
const sdk = getSdk(client);
const { continents } = await sdk.continents(); // This is fully typed, based on the query
console.log(`GraphQL data:`, continents);

Simple Request Middleware#

The generated sdk accepts an optional middleware function to wrap the requests the client makes.

This can enable scenarios like request failure retries and logging at the sdk level.

To use middleware, just pass an SdkFunctionWrapper as the second argument to getSdk.

// `SdkFunctionWrapper` is a type we provide. `action` is the `client` request execution generated by this template. The wrapper MUST invoke `action()` and should return the promise returned by `action`, or its resolution.
type SdkFunctionWrapper = <T>(action: () => Promise<T>) => Promise<T>;

Examples of Middleware#

  • This example shows a naive request timing logger.
const client = new GraphQLClient('');
const clientTimingWrapper: SdkFunctionWrapper = async <T>(action: () => Promise<T>): Promise<T> => {
const startTime = new Date();
const result = await action();
console.log('request duration (ms)', new Date() - startTime)
return result;
const sdk = getSdk(client, clientTimingWrapper);
  • This example uses polly-js to define a failure retry wrapper. (this is the use case for which i originally intended to add this capability)
const withRetries: RetryWrapper = <T>(action: () => Promise<T>) =>
.handle((err: Error) => {
warn('GraphqlClient:NetworkError', err);
return err.message.includes('connect ETIMEDOUT');
.executeForPromise(info => {
if (info.count === 3) {
error('GraphqlClient:MaxRetries', null, {,
action: action.toString(),
} else if (info.count > 0) {
warn('GraphqlClient:RetryingCall', null, {,
action: action.toString(),
return action();
const sdk = getSdk(client, withRetries);