@datocms/cda-client

中文文档
0.3.2发布于 2026/09/04MITTypeScriptESM + CJS近 30 天下载 36.5万

JS client for DatoCMS GraphQL Content Delivery API based on the browser Fetch API

原始使用文档
文档目录19 节
  1. TypeScript Support
  2. Examples
  3. Basic Query Execution
  4. Using with TypeScript and GraphQL Code Generator
  5. Installation
  6. Usage
  7. executeQuery
  8. rawExecuteQuery
  9. executeQueryWithAutoPagination
  10. How does it work?
  11. rawExecuteQueryWithAutoPagination
  12. buildRequestHeaders
  13. buildRequestInit
  14. Error Handling
  15. Example
  16. Contributing
  17. Trying a change before it's released
  18. Releasing (maintainers)
  19. License

👉 Visit the DatoCMS homepage or see What is DatoCMS?


@datocms/cda-client

A lightweight, TypeScript-ready package that offers various helpers around the native Fetch API to perform GraphQL requests towards DatoCMS Content Delivery API.

TypeScript Support

This package is built with TypeScript and provides type definitions out of the box. It supports TypedDocumentNode for improved type inference when using gql.tada, GraphQL Code Generator or similar tools.

Examples

Basic Query Execution

import { executeQuery } from "@datocms/cda-client";

const query = `
  query {
    allArticles {
      id
      title
    }
  }
`;

const result = await executeQuery(query, {
  token: "your-api-token-here",
});

console.log(result);

Using with TypeScript and GraphQL Code Generator

import { executeQuery } from "@datocms/cda-client";
import { AllArticlesQuery } from "./generated/graphql";

const result = await executeQuery(AllArticlesQuery, {
  token: "your-api-token-here",
  variables: {
    limit: 10,
  },
});

console.log(result.allArticles);

Installation

npm install @datocms/cda-client

Usage

This package provides several utility functions to help you interact with the DatoCMS Content Delivery API using GraphQL.

executeQuery

The main function to execute a GraphQL query against the DatoCMS Content Delivery API.

import { executeQuery } from "@datocms/cda-client";

const result = await executeQuery(query, options);

Parameters

  • query: A GraphQL query string, DocumentNode, or TypedDocumentNode.
  • options: An object containing execution options.

Options

OptionTypeDescription
tokenstringDatoCMS API token (required) Read more
includeDraftsbooleanIf true, return draft versions of records Read more
excludeInvalidbooleanIf true, filter out invalid records Read more
environmentstringName of the DatoCMS environment for the query Read more
contentLink'vercel-v1'If true, embed metadata for Content Link Read more
baseEditingUrlstringBase URL of your DatoCMS project Read more
returnCacheTagsbooleanIf true, receive Cache Tags associated with the query Read more
variablesobjectVariables to be sent with the query
fetchFnfunctionCustom fetch function (optional)
requestInitOptionsPartial<RequestInit>Additional request initialization options (optional)
autoRetrybooleanAutomatically retry on rate limit (default: true)

rawExecuteQuery

Similar to executeQuery, but returns both the query result and the full response object. This can be handy when used together with returnCacheTags to actually retrieve the cache tags.

import { rawExecuteQuery } from "@datocms/cda-client";

const [result, response] = await rawExecuteQuery(query, {
  token: "your-api-token-here",
  returnCacheTags: true,
});
const cacheTags = response.headers.get("x-cache-tags");

executeQueryWithAutoPagination

This function comes handy when the query contains a paginated collection: behind the scene, executeQueryWithAutoPagination reworks the passed query and collects the results, so that it's possible to get a collection of records that is longer than Content Delivery API's result limit. That is done with a single API call, in a transparent way.

import { executeQueryWithAutoPagination } from "@datocms/cda-client";

const result = await executeQueryWithAutoPagination(query, options);

Parameters

Parameters are the same available for executeQuery:

  • query: A GraphQL query string, DocumentNode, or TypedDocumentNode.
  • options: An object containing execution options with the same shape of options for executeQuery.

How does it work?

Suppose you want to execute the following query on an model with 2500 records:

query BuildSitemapUrls {
  allBlogPosts {
    slug
  }

  entries: allSuccessStories(first: 2500) {
    ...SuccessStoryUrlFragment
  }
}

fragment SuccessStoryUrlFragment on SuccessStoryRecord {
  slug
}

Well, that's a roadblock: The CDA is limited to returning a maximum of 500 items at a time. If you try to fetch more than that, you'll get an error. Instead, if you wanted to fetch all 2500 records, you would normally have to manually paginate it by executing the query multiple times, each time incrementing the skip parameter by an additional 500. That's a lot of work!

Fortunately, the helper function executeQueryWithAutoPagination does that on your behalf: the above query is analyzed and rewritten on the fly like this:

query BuildSitemapUrls {
  allBlogPosts {
    slug
  }
  splitted_0_entries: allSuccessStories(first: 500, skip: 0) {
    ...SuccessStoryUrlFragment
  }
  splitted_500_entries: allSuccessStories(first: 500, skip: 500) {
    ...SuccessStoryUrlFragment
  }
  splitted_1000_entries: allSuccessStories(first: 500, skip: 1000) {
    ...SuccessStoryUrlFragment
  }
  splitted_1500_entries: allSuccessStories(first: 500, skip: 1500) {
    ...SuccessStoryUrlFragment
  }
  splitted_2000_entries: allSuccessStories(first: 500, skip: 2000) {
    ...SuccessStoryUrlFragment
  }
}

fragment SuccessStoryUrlFragment on SuccessStoryRecord {
  slug
}

Once executed, the results get collected and recomposed as if nothing happened.

Limitations

executeQueryWithAutoPagination works only when the query contains only one selection that has an oversized first: argument (i.e. the first: argument surpasses the Content Delivery API's result limit of 500). If two or more requested models have oversized pagination, the function will return an error.

The rewritten query must still respect the GraphQL complexity cost.

rawExecuteQueryWithAutoPagination

As for executeQuery, also executeQueryWithAutoPagination has a pair raw version that returns both the query result and the full response object. This can be handy when used together with returnCacheTags to actually retrieve the cache tags.

import { rawExecuteQueryWithAutoPagination } from "@datocms/cda-client";

const [result, response] = await rawExecuteQueryWithAutoPagination(query, {
  token: "your-api-token-here",
  returnCacheTags: true,
});
const cacheTags = response.headers.get("x-cache-tags");

buildRequestHeaders

Builds request headers for a GraphQL query towards the DatoCMS Content Delivery API.

import { buildRequestHeaders } from "@datocms/cda-client";

const headers = buildRequestHeaders(options);

Options

The buildRequestHeaders function accepts the same options as executeQuery, except for variables, fetchFn, and autoRetry.

buildRequestInit

Builds the request initialization object for a GraphQL query towards the DatoCMS Content Delivery API.

import { buildRequestInit } from "@datocms/cda-client";

const requestInit = buildRequestInit(query, options);

Parameters

  • query: A GraphQL query string or DocumentNode.
  • options: An object containing execution options (same as executeQuery).

Error Handling

In case a query fails (either with an HTTP status code outside of the 2xx range, or for an error in the query), an ApiError exception will be thrown by the client. This error contains all the details of the request and response, allowing you to debug and handle errors effectively.

Example

import { executeQuery, ApiError } from "@datocms/cda-client";

const query = `
  query {
    allArticles {
      id
      title
    }
  }
`;

try {
  const result = await executeQuery(query, {
    token: "your-api-token-here",
  });
  console.log(result);
} catch (e) {
  if (e instanceof ApiError) {
    // Information about the failed request. The API token is redacted from
    // `e.options`: an error tends to end up in logs and error trackers, which
    // are no place for a token.
    console.log(e.query);
    console.log(e.options);

    // Information about the response
    console.log(e.response.status);
    console.log(e.response.statusText);
    console.log(e.response.headers);
    console.log(e.response.body);
  } else {
    // Handle other types of errors
    throw e;
  }
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Trying a change before it's released

Every push to a branch here publishes a preview of the package, which you can install anywhere — no npm release, no npm link:

npm i https://pkg.pr.new/@datocms/cda-client@<commit-sha>

The exact URL shows up in the commit's check run on GitHub, and in a comment on the pull request once there is one. This is the supported way to try a change inside a site that lives in another repository, or to hand a fix to whoever reported it before it is released.

Previews are throwaway: they are never published to npm, and the URL stops resolving after a while. Never commit one to a package.json that ships.

Releasing (maintainers)

Every user-visible change needs a changeset: run npx changeset from the repo root in the same PR, pick the bump level (patch is for bug fixes only, new API surface is minor) and commit the file it writes under .changeset/. That is where the changelog entry comes from, and it is where the bump level is decided — not on release day. See .changeset/README.md.

To release, from an up-to-date, clean main, run npm run release. It builds and tests, applies the pending changesets — bumping the version and writing CHANGELOG.md — publishes to npm, and only then tags vX.Y.Z, pushes, and creates a GitHub release whose notes come straight from that changelog entry. An interrupted release is resumed by re-running it, never undone. Use npm run release:next for a prerelease under the next dist-tag.

The script is @datocms/release-toolchain, shared with every other DatoCMS repository and pinned here by tag.

License

This project is licensed under the MIT License.


What is DatoCMS?

DatoCMS - The Headless CMS for the Modern Web

DatoCMS is Headless CMS for the modern web. Trusted by 25,000+ businesses, agencies, and individuals, it gives your team one place to manage content and ship it to any website, app, or device via API.

New here? Start with Create free account and the Documentation. Stuck? Ask the Community. Curious what's new? Product Updates.

Building with AI: Agent Skills turn coding assistants (Claude Code, Cursor) into expert DatoCMS developers, with full read/write via the auto-installed CLI. No local terminal? Use the MCP Server instead.

Talking to DatoCMS from code:

  • Content Delivery API (CDA) — the fast, read-only GraphQL API your website/app uses to fetch published content.
  • Content Management API (CMA) — the REST API for creating and updating content, models, and project settings (think scripts, migrations, integrations).
  • CLI — terminal tool for schema migrations and importing from Contentful/WordPress.

Framework guides: end-to-end recipes for fetching content, rendering Structured Text, optimizing images/video, handling SEO, and setting up live preview with visual editing in Next.js, Nuxt, Svelte, and Astro.

Want a head start? Browse our starter projects — ready-to-deploy example sites for popular frameworks.

版本与发布记录

@datocms/cda-client 共发布 21 个版本,首次发布于 2024/07/25;过去 12 个月发布了 6 个版本。

版本发布日期距今
0.3.2latest2026/09/042 个月前
0.3.12026/08/312 个月前
0.3.02026/08/152 个月前
0.2.102025/12/2310 个月前
0.2.92025/12/1210 个月前
0.2.82025/12/1210 个月前

关于 @datocms/cda-client 的常见问题

@datocms/cda-client 是什么?

JS client for DatoCMS GraphQL Content Delivery API based on the browser Fetch API

如何安装 @datocms/cda-client?

在项目目录运行 npm install @datocms/cda-client,或使用 pnpm add / yarn add / bun add。

@datocms/cda-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@datocms/cda-client 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@datocms/cda-client 可以商用吗?

@datocms/cda-client 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@datocms/cda-client 的下载量有多少?

根据 npm 官方下载统计,@datocms/cda-client 在 2026/10/12 – 2026/11/10 这 30 天内被下载 364,960 次,日均约 12,165 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@datocms/cda-client 还在维护吗?

最新版本 0.3.2 发布于 2026/09/04(2 个月前);至今共发布 21 个版本,其中过去 12 个月发布了 6 个;首次发布于 2024/07/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。