@cosmicjs/sdk

中文文档
2.4.0发布于 2026/09/10MITTypeScriptESM + CJS零依赖近 30 天下载 1万

Official JavaScript SDK for Cosmic. Fetch content, manage media, and generate AI in Next.js, Node, and the browser.

原始使用文档
文档目录26 节
  1. Quick start
  2. Install
  3. Contents
  4. Authentication
  5. Get Objects
  6. Get multiple Objects [ see docs ]
  7. Get a single Object [ see docs ]
  8. Typed results
  9. Query helpers
  10. Create, update, and delete Objects
  11. Create Object [ see docs ]
  12. Update Object [ see docs ]
  13. Delete Object [ see docs ]
  14. Batch operations [ see docs ]
  15. Media
  16. Object types
  17. Revisions
  18. Rich text and blocks
  19. AI
  20. Text
  21. Image, video, and audio
  22. Learn more
  23. Community support
  24. Cosmic support
  25. Contributing
  26. License

Cosmic

Cosmic JavaScript SDK

The official client for Cosmic. Fetch content, manage media, and generate AI in Next.js, Node, and the browser.

npm version npm downloads TypeScript Node.js >= 18 Package Checks MIT License

Get started free · Quickstart · Examples · Next.js guide

Cosmic is a headless CMS with a dashboard for creating content and an API for delivering it to any website or application. This package is the official TypeScript client: typed results, zero runtime dependencies, works in Next.js, Node.js 18+, and the browser.

Quick start

Install the SDK, add your Bucket keys from Bucket > Settings > API Access, and fetch content in a Next.js App Router page.

npm install @cosmicjs/sdk
COSMIC_BUCKET_SLUG=your-bucket-slug
COSMIC_READ_KEY=your-read-key
import { createBucketClient } from '@cosmicjs/sdk';

const cosmic = createBucketClient({
  bucketSlug: process.env.COSMIC_BUCKET_SLUG as string,
  readKey: process.env.COSMIC_READ_KEY as string,
});

export default async function HomePage() {
  const { objects: posts } = await cosmic.objects
    .find({ type: 'posts' })
    .props(['id', 'slug', 'title', 'metadata'])
    .limit(10);

  return (
    <main>
      <h1>Latest posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <a href={`/posts/${post.slug}`}>{post.title}</a>
          </li>
        ))}
      </ul>
    </main>
  );
}

Pass a type parameter when you want a specific shape: find<Post>({ type: 'posts' }).

Browse starter apps →

Install

npm install @cosmicjs/sdk
# or
yarn add @cosmicjs/sdk
# or
bun add @cosmicjs/sdk
import { createBucketClient } from '@cosmicjs/sdk';

Contents

Authentication

In the Cosmic admin dashboard go to Bucket > Settings > API Access and copy your Bucket slug and keys.

const cosmic = createBucketClient({
  bucketSlug: process.env.COSMIC_BUCKET_SLUG,
  readKey: process.env.COSMIC_READ_KEY,
});

Add writeKey for create, update, delete, media uploads, and AI. Never expose a write key in client-side code.

const cosmic = createBucketClient({
  bucketSlug: process.env.COSMIC_BUCKET_SLUG,
  readKey: process.env.COSMIC_READ_KEY,
  writeKey: process.env.COSMIC_WRITE_KEY,
});

Add previewToken to read drafts in live preview without a write key.

const cosmic = createBucketClient({
  bucketSlug: process.env.COSMIC_BUCKET_SLUG,
  readKey: process.env.COSMIC_READ_KEY,
  previewToken: process.env.COSMIC_PREVIEW_TOKEN,
});

Get Objects

Objects are the basic building blocks of content in Cosmic. Pass a generic to type the result, or use CosmicObject for the common fields.

Get multiple Objects [see docs]

const { objects: posts } = await cosmic.objects
  .find({
    type: 'posts',
  })
  .props(['title', 'slug', 'metadata'])
  .limit(10);

Get a single Object [see docs]

const { object: page } = await cosmic.objects
  .findOne({
    type: 'pages',
    slug: 'home',
  })
  .props(['title', 'slug', 'metadata']);

Typed results

type Post = {
  title: string;
  slug: string;
  metadata: { excerpt: string };
};

const { objects } = await cosmic.objects
  .find<Post>({ type: 'posts' })
  .props(['title', 'slug', 'metadata']);

Query helpers

Chain these on find and findOne:

MethodPurpose
.props(['title', 'slug'])Return only the listed fields
.limit(10)Page size (find only)
.skip(20)Offset for pagination
.sort('-created_at')Sort by field. Prefix - for descending
.depth(1)Resolve nested Object references
.status('published')published, draft, or any
.after(id)Cursor pagination
.useCache()Enable the Cosmic CDN cache

Create, update, and delete Objects

Requires a writeKey.

Create Object [see docs]

await cosmic.objects.insertOne({
  title: 'Blog Post Title',
  type: 'posts',
  metadata: {
    content: 'Here is the blog post content.',
    seo_description: 'This is the blog post SEO description.',
    featured_post: true,
    tags: ['javascript', 'cms'],
  },
});

Update Object [see docs]

await cosmic.objects.updateOne('object-id', {
  metadata: {
    content: 'Updated blog post content.',
    featured_post: false,
  },
});

Delete Object [see docs]

await cosmic.objects.deleteOne('object-id');

Batch operations [see docs]

Create, update, and delete up to 25 Objects in one call. Each operation succeeds or fails independently.

const result = await cosmic.objects.batch([
  { method: 'add', object: { title: 'Post 1', type: 'posts', metadata: { content: '...' } } },
  { method: 'edit', object_id: 'object-id', object: { title: 'Updated Title' } },
  { method: 'delete', object_id: 'another-object-id' },
]);

Media

Upload, list, and delete files in the Media Library. [see docs]

const { media } = await cosmic.media
  .find({ folder: 'images' })
  .props(['name', 'url', 'imgix_url'])
  .limit(20);

const { media: file } = await cosmic.media.findOne({ name: 'hero.png' });

await cosmic.media.insertOne({
  media: bufferOrFile,
  folder: 'images',
});

await cosmic.media.updateOne('media-id', { alt_text: 'Hero image' });
await cosmic.media.deleteOne('media-id');

Uploaded images include an imgix_url for resizing and optimization.

Object types

Read and manage the content model. [see docs]

const { object_types } = await cosmic.objectTypes.find();
const { object_type } = await cosmic.objectTypes.findOne('posts');

await cosmic.objectTypes.insertOne({ title: 'Authors', slug: 'authors' });
await cosmic.objectTypes.updateOne('authors', { title: 'Writers' });
await cosmic.objectTypes.deleteOne('authors');

Revisions

List and restore Object revisions. Combine with previewToken to preview drafts. [see docs]

const { revisions } = await cosmic.objectRevisions.find('object-id');
const { revision } = await cosmic.objectRevisions.findOne({
  objectId: 'object-id',
  revisionId: 'revision-id',
});

Rich text and blocks

Fetch Rich Text block definitions and render them with @cosmicjs/rich-text. [see docs]

npm install @cosmicjs/rich-text
import { createBucketClient } from '@cosmicjs/sdk';
import { RichText } from '@cosmicjs/rich-text';

const cosmic = createBucketClient({
  bucketSlug: process.env.COSMIC_BUCKET_SLUG as string,
  readKey: process.env.COSMIC_READ_KEY as string,
});

const [{ object: post }, { blocks }] = await Promise.all([
  cosmic.objects.findOne({ type: 'posts', slug: 'hello-world' }),
  cosmic.blocks.find(),
]);

export default function Post() {
  return <RichText value={post?.metadata.content} blocks={blocks} />;
}

AI

Generate text, images, video, and audio. Requires a writeKey. [see docs]

Text

const { text, usage } = await cosmic.ai.generateText({
  prompt: 'Write a product description for a coffee mug',
  max_tokens: 500,
});

Stream tokens as they arrive. stream: true returns a TextStreamingResponse; no cast needed.

const stream = await cosmic.ai.generateText({
  prompt: 'Tell me about coffee mugs',
  stream: true,
});

for await (const chunk of stream) {
  if (chunk.text) process.stdout.write(chunk.text);
}

Or use cosmic.ai.stream({ prompt }). Analyze images by passing media_url with your prompt.

Image, video, and audio

const image = await cosmic.ai.generateImage({
  prompt: 'A serene mountain landscape at sunset',
  folder: 'ai-generated-images',
});

const icon = await cosmic.ai.generateImage({
  prompt: 'Minimal coffee cup icon, flat vector, no text',
  format: 'svg',
  aspect_ratio: '1:1',
});

const video = await cosmic.ai.generateVideo({
  prompt: 'Product rotates smoothly with soft studio lighting',
  duration: 8,
  resolution: '720p',
});

const extended = await cosmic.ai.extendVideo({
  media_id: video.media.id,
  prompt: 'The camera pulls back to reveal the full scene',
});

const audio = await cosmic.ai.generateAudio({
  prompt: 'Welcome to the Cosmic Developer Podcast.',
  voice: 'nova',
});

Generated files are saved to your Media Library with CDN URLs. See the AI Video Generation Guide for models, duration, and extension details, and examples/ for runnable scripts.

Learn more

Community support

  • Discord (questions, bug reports)
  • GitHub (issues, contributions)
  • X (product updates)
  • YouTube (video tutorials)

Cosmic support

Contact us for service questions and custom plans.

Contributing

This project uses changeset to manage releases. Follow the following steps to add a changeset:

  • Run npm run changeset command and select type of release with description of changes.
  • When PR with changeset is merged into main branch, Github will create a new PR with correct version change and changelog edits.
  • When codeowner merges the generated PR, it will publish the package and create a Github release.

License

This project is published under the MIT license.

版本与发布记录

@cosmicjs/sdk 共发布 53 个版本,首次发布于 2023/03/24;过去 12 个月发布了 9 个版本。

版本发布日期距今
2.4.0latest2026/09/102 个月前
2.3.02026/09/032 个月前
2.2.02026/09/012 个月前
2.1.02026/06/095 个月前
2.0.12026/04/087 个月前
2.0.02026/04/087 个月前

其他发布通道:alt-text → 1.0.12,canary → 1.0.16,ai → 1.4.5,browser-fix → 1.5.3。

关于 @cosmicjs/sdk 的常见问题

@cosmicjs/sdk 是什么?

Official JavaScript SDK for Cosmic. Fetch content, manage media, and generate AI in Next.js, Node, and the browser.

如何安装 @cosmicjs/sdk?

在项目目录运行 npm install @cosmicjs/sdk,或使用 pnpm add / yarn add / bun add。

@cosmicjs/sdk 支持 TypeScript 吗?

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

@cosmicjs/sdk 支持 ESM 还是 CommonJS?

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

@cosmicjs/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cosmicjs/sdk 可以商用吗?

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

@cosmicjs/sdk 的下载量有多少?

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

@cosmicjs/sdk 还在维护吗?

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