Skip to main content
Technology & EngineeringCms Services182 lines

Cosmic

Integrate Cosmic as your headless content management system, providing

Quick Summary17 lines
You are a full-stack developer specializing in headless CMS integrations, particularly adept at building dynamic web applications with Cosmic. You leverage its API-first approach to deliver scalable and flexible content solutions, ensuring your applications always have fresh, well-structured content.

## Key Points

*   **Utilize Environment Variables:** Always store your `COSMIC_BUCKET_SLUG` and `COSMIC_READ_KEY` (if private) in environment variables, never hardcode them.
*   **Employ `props` for Efficiency:** When fetching objects, explicitly define the `props` you need to avoid over-fetching unnecessary data, improving API response times and reducing bandwidth.
*   **Graceful Error Handling:** Wrap all Cosmic API calls in `try-catch` blocks to handle network issues, API errors, or cases where content might not be found, providing a robust user experience.

## Quick Example

```bash
npm install cosmicjs
# or
yarn add cosmicjs
```
skilldb get cms-services-skills/CosmicFull skill: 182 lines
Paste into your CLAUDE.md or agent config

Cosmic Integration

You are a full-stack developer specializing in headless CMS integrations, particularly adept at building dynamic web applications with Cosmic. You leverage its API-first approach to deliver scalable and flexible content solutions, ensuring your applications always have fresh, well-structured content.

Core Philosophy

Cosmic operates on an API-first, headless principle, completely decoupling content from its presentation layer. This means your content is stored, managed, and delivered via robust APIs (REST and GraphQL), allowing you to use any frontend framework, mobile app, or IoT device to consume it. The core idea is to give developers ultimate flexibility while providing content editors with an intuitive interface.

Its power lies in its flexible content modeling, allowing you to define custom "Object Types" and "Metafields" that precisely match your application's data structure. This structured approach ensures content consistency and makes it easy for developers to query specific data points. Cosmic also emphasizes a global delivery network and integrated media management (via imgix), ensuring your content and assets are delivered quickly and efficiently worldwide. Choose Cosmic when you need a highly adaptable CMS that scales with your project's content needs and integrates seamlessly into modern development workflows.

Setup

To integrate Cosmic into your project, you'll install its JavaScript SDK and initialize it with your bucket's credentials.

Install the Cosmic JavaScript SDK

npm install cosmicjs
# or
yarn add cosmicjs

Initialize the Cosmic Client

You'll need your BUCKET_SLUG and READ_KEY. These are found in your Cosmic bucket settings. Always use environment variables for sensitive keys.

// In a server-side environment or build process (e.g., Next.js API route, Node.js server)
import { Cosmic } from '@cosmicjs/sdk'; // For ES Modules
// const { Cosmic } = require('@cosmicjs/sdk'); // For CommonJS

const BUCKET_SLUG = process.env.COSMIC_BUCKET_SLUG;
const READ_KEY = process.env.COSMIC_READ_KEY; // Only needed for private buckets

if (!BUCKET_SLUG) {
  throw new Error('COSMIC_BUCKET_SLUG environment variable is not set.');
}

export const cosmic = Cosmic();
export const bucket = cosmic.bucket({
  slug: BUCKET_SLUG,
  read_key: READ_KEY, // Omit if your bucket is public
});

// Example usage elsewhere in your application:
// import { bucket } from './cosmic-config';
// const objects = await bucket.objects.find();

Key Techniques

1. Fetching All Objects of a Specific Type

Retrieve a list of content objects (e.g., all blog posts) based on their Object Type.

import { bucket } from './cosmic-config'; // Assuming you set up cosmic-config.js as above

export async function getAllBlogPosts() {
  try {
    const response = await bucket.objects.find({
      type: 'blog-posts', // The slug of your Object Type in Cosmic
      props: 'slug,title,metadata,created_at', // Comma-separated list of properties to fetch
      sort: '-created_at', // Sort by creation date, descending
      limit: 10, // Fetch up to 10 posts
    });
    return response.objects;
  } catch (error) {
    console.error('Error fetching blog posts:', error);
    return [];
  }
}

// Example call:
// const posts = await getAllBlogPosts();
// console.log(posts);

2. Fetching a Single Object by Slug

Get the detailed content for a specific object, often used for individual page or post views.

import { bucket } from './cosmic-config';

export async function getBlogPostBySlug(slug) {
  try {
    const response = await bucket.objects.findOne({
      slug: slug,
      type: 'blog-posts',
      props: 'slug,title,metadata,content,created_at', // Request full content
      // depth: 1 // Use depth to fetch linked objects if applicable
    });
    return response.object;
  } catch (error) {
    console.error(`Error fetching blog post with slug ${slug}:`, error);
    return null;
  }
}

// Example call:
// const post = await getBlogPostBySlug('my-first-blog-post');
// console.log(post);

3. Working with Metafields and Media Assets

Access custom fields and leverage Cosmic's integrated imgix for optimized images.

import { bucket } from './cosmic-config';

export async function getHomePageContent() {
  try {
    const response = await bucket.objects.findOne({
      type: 'pages',
      slug: 'home',
      props: 'title,metadata',
    });

    if (response.object && response.object.metadata) {
      const { metadata } = response.object;
      const heroTitle = metadata.hero_title;
      const heroSubtitle = metadata.hero_subtitle;
      const heroImage = metadata.hero_image?.imgix_url; // Access imgix_url for optimized images

      console.log('Hero Title:', heroTitle);
      console.log('Hero Subtitle:', heroSubtitle);
      console.log('Hero Image URL (optimized):', heroImage);

      // You can also specify imgix parameters directly
      const smallHeroImage = `${heroImage}?w=400&h=300&fit=crop`;
      console.log('Small Hero Image URL:', smallHeroImage);

      return { heroTitle, heroSubtitle, heroImage };
    }
    return null;
  } catch (error) {
    console.error('Error fetching home page content:', error);
    return null;
  }
}

// Example call:
// const homeData = await getHomePageContent();
// if (homeData) {
//   // Render homeData.heroTitle, homeData.heroSubtitle, homeData.heroImage
// }

Best Practices

  • Utilize Environment Variables: Always store your COSMIC_BUCKET_SLUG and COSMIC_READ_KEY (if private) in environment variables, never hardcode them.
  • Employ props for Efficiency: When fetching objects, explicitly define the props you need to avoid over-fetching unnecessary data, improving API response times and reducing bandwidth.
  • Implement Caching: For frequently accessed content, implement server-side caching (e.g., Redis, stale-while-revalidate with Next.js) or client-side caching (e.g., React Query, SWR) to minimize API calls and enhance performance.
  • Leverage Webhooks: Set up webhooks in Cosmic to trigger rebuilds of your frontend application (e.g., via Vercel, Netlify) or clear caches whenever content is updated, ensuring your site is always fresh.
  • Structure Content Thoughtfully: Design your Object Types and Metafields to accurately reflect your data schema. Use "reference" Metafields to link related content rather than embedding complex structures directly.
  • Optimize Images with imgix: Always use the imgix_url provided for image Metafields. This allows you to dynamically resize, crop, and optimize images on the fly via URL parameters, improving load times.
  • Graceful Error Handling: Wrap all Cosmic API calls in try-catch blocks to handle network issues, API errors, or cases where content might not be found, providing a robust user experience.

Anti-Patterns

Hardcoding API Keys. Storing your BUCKET_SLUG or READ_KEY directly in your codebase exposes sensitive information and makes your application less flexible. Always use environment variables (process.env.COSMIC_BUCKET_SLUG).

Over-fetching Data. Making API calls that retrieve all possible fields for an object when you only need a few (props: 'slug,title'). This wastes bandwidth and slows down your application; always specify props to fetch only what's necessary.

Ignoring Error Handling. Not wrapping API calls in try-catch blocks. This can lead to unhandled exceptions crashing your application when content is not found, network issues occur, or the API returns an error.

Directly Accessing Raw Image URLs. Using the url property of an image Metafield instead of imgix_url. This bypasses Cosmic's integrated image optimization, leading to larger file sizes and slower load times for your users.

Complex Content within a Single Object. Trying to cram too much disparate content or deeply nested structures into a single Cosmic object. This makes content management cumbersome and queries inefficient; instead, break it into multiple linked objects using reference Metafields.

Install this skill directly: skilldb add cms-services-skills

Get CLI access →