@cosmicjs/sdk

Official JavaScript SDK for Cosmic. Fetch content, manage media, and generate AI in Next.js, Node, and the browser.
129,302 18
Install
npm install @cosmicjs/sdk
Latest Version:2.4.0
License:MIT
Last Updated:Sep 9, 2026
Links: GitHub  ·  npm
Maintainer: tonyspiro

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:

Method Purpose
.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

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.

Related Packages

@easy-cms/core

Embedded, code-first headless CMS for Nuxt and Next.js

25,029 2
@preprio/toolkit

Prepr personalization, A/B testing and preview toolkit for React, Next.js, Nuxt,...

8,356 1
@inneropen/marvin-sdk

Official TypeScript SDK for Marvin CMS

19,254 0
create-contioreach-blog

Create a blog wired to ContioReach in one command. Pick Next.js, Nuxt, Astro, Sv...

479 0
astro-vscode

Language support for Astro

18,973 63,402

Version History

Version Released License
2.4.0 MIT
2.3.0 MIT
2.2.0 MIT
2.1.0 MIT
2.0.1 MIT