npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cosmicjs/sdk

v2.4.0

Published

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

Readme

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

  • 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.