Cosmic Documentation

website·Indexed 36 days ago

https://docs-v3.cosmicjs.com/

Documentation for Cosmic, a headless CMS. Includes guides for the admin dashboard, project and bucket management, and a comprehensive REST API reference covering authentication, object types, queries, media, webhooks, and request limits.

Tokens
12K
Snippets
58
Records
95
Agent score
51%

What's inside Cosmic

  1. Query Objects and Media in Cosmic

    Cosmic allows fetching content from a Bucket using queries that match exact structures (fields, metadata values, dates, and ranges). Queries are passed as objects to the find method of the objects or media clients. If accessing the API via a browser URL, curly braces {} must be URL-encoded as %7B and %7D.
  2. Handle Cosmic API error responses

    When a request fails, the Cosmic API returns a JSON response containing the HTTP status code and a verbose error message to help diagnose the issue. The message field provides specific details about the failure, such as validation errors for metafields.
    {
      "status": 400,
      "message": "Metafield validation: invalid 'value' for metafield with key: 'number' and type: 'number'"
    }
  3. Understand Cosmic Buckets and Object Types

    Buckets are the primary containers for managing Cosmic content, media, extensions, and add-ons. Within a Bucket, you organize content using Object types (content models). Object types can be configured as 'multiple' or 'singletons'. Each Object type includes a slug used for API requests. Optional features for Object types include emojis for dashboard organization, localization for multi-language support, and preview links for live site testing.
  4. Understand the Cosmic Object model properties

    Objects are the fundamental building blocks of content in a Cosmic Bucket. Each Object contains core system properties and custom Metafields.

    Core Properties:

    • id: Unique identifier for the Object.
    • slug: Unique identifier per Object type. Localized versions share the same slug.
    • title: The title of the Object.
    • type: The slug of the Object type.
    • status: Current state (published or draft).
    • metadata: A JSON object containing the values of the Metafields defined for the Object type.
    • created_at / modified_at: Timestamps for creation and last modification.
    • published_at: Timestamp of the last publication.
    • publish_at / unpublish_at: UNIX millisecond timestamps for scheduled publishing/unpublishing.
    • modified_by: ID of the user who last modified the Object.

    Note: The HTML Content property is deprecated in API v3; use Metafields instead.

    {
      "id": "63dc57ca24090e0008683d42",
      "slug": "add-a-headless-cms-to-astro-in-3-easy-steps",
      "title": "Add a headless CMS to Astro in 3 easy steps",
      "bucket": "63dc24a4d71e244b63c88fca",
      "created_at": "2023-02-03T00:39:38.35Z",
      "modified_at": "2023-03-23T12:08:13.547Z",
      "status": "published",
      "thumbnail": "https://imgix.cosmicjs.com/...",
      "published_at": "2023-03-23T12:08:13.547Z",
      "modified_by": "629e6cdda6f4f100091ae2e0",
      "publish_at": null,
      "type": "blog-posts",
      "metadata": {
        "content": "Astro is a lightweight web framework...",
        "image": {
          "url": "https://cdn.cosmicjs.com/..."
        },
        "published_date": "2022-09-20",
        "author": {
          "title": "Bill Brasky"
        }
      }
    }
  5. Build and integrate custom Extensions

    Extensions are iframes that connect third-party APIs to the Cosmic dashboard. Requirements: The URL must be served via https:// and have X-Frame Options enabled. Extensions can be placed in the following locations:

    • Full page (Project/Bucket/Extensions)
    • Add Object page (below title, slug, Metafields, or in actions sidebar)
    • Edit Object page (below title, slug, Metafields, or in actions sidebar)
    • Media modal (as an additional tab)
  6. Configure Webhooks for third-party services

    Webhooks send HTTP POST requests to third-party services when specific events occur in a Bucket. To create a webhook, navigate to Bucket > Settings > Webhooks and select "Add Webhook". For testing and viewing response data, tools like Beeceptor are recommended.
  7. Update Object metadata

    Update basic Metafields (text, numbers, booleans) by passing a metadata object during a create or update request. Use the key:value format where the key matches the Metafield key defined in the Object type.
    await cosmic.objects.updateOne('object-id', {
      metadata: {
        headline: 'This guitar amp is LOUD!',
        max_volume: 11,
        on_sale: true
      }
    })
    
  8. Model content using Object types and Objects

    Content in Cosmic is structured using Object types and individual Objects:

    • Object types: These define the data model (e.g., 'pages', 'blog posts', 'authors'). You define the model using Metafields, which support plain text, rich text, numbers, color pickers, select/multi-select dropdowns, switches, media (image/video), and Object relationships.
    • Objects: These are the actual content entries. To create one, navigate to an Object type table and click '+ Add Object'.
  9. Promote content between Buckets

    Promote content to move selected Objects from one Bucket to another within the same Project. This is typically used for staging-to-production workflows.

    Ways to initiate promotion:

    • Bulk Action: Bucket > Content > [Object Type] > select Objects > click Promote.
    • Single Row: Click the three-dot menu on an Object row > Promote to Bucket.
    • Detail View: Open an Object > click the three-dot menu at the top.

    What is copied:

    • Objects: Title, content, Metafields, thumbnail, status, and slug.
    • Object Types: Automatically created in the target Bucket if they don't exist using the source schema.
    • Media: Referenced media (thumbnails, file Metafields, embedded URLs) is copied to the target Media Library. Existing media is reused to prevent duplicates.
    • Object References: Remapped to matching Objects in the target Bucket based on type, slug, and locale.
    • Revisions: A new revision is saved for every created, updated, or cascaded Object.

    Permissions: Requires write access on both source and target Buckets. Schema-altering actions may require a Project admin role.

  10. Monitor workspace usage and audit logs

    Navigate to Workspace > Usage to track resource consumption. Available tools include:

    • Month-to-date usage: View totals for projects, team, Buckets, media, and API requests.
    • Analytics tab: View historical data (Note: Analytics data is retained for 90 days).
    • Activity > Audit log: (Admin only) Track user actions across all projects in the workspace, filterable by user, action, or date range.
  11. Authenticate Cosmic API requests using Bucket keys

    Cosmic uses Bucket slugs and API keys to authenticate requests for content management. You can find these credentials in the Cosmic dashboard under Bucket Settings > API Access.

    Security Warning: Never expose your Bucket write key in client-side code.

    import { createBucketClient } from '@cosmicjs/sdk';
    
    const cosmic = createBucketClient({
      bucketSlug: 'BUCKET_SLUG',
      readKey: 'BUCKET_READ_KEY',
      writeKey: 'BUCKET_WRITE_KEY',
    });
    
    // Fetch content
    await cosmic.objects.find({ type: 'posts' }).limit(1);
    
    // Write content
    await cosmic.objects.insertOne({
      title: 'Blog Post Title',
      type: 'posts',
      metadata: { content: '...' },
    });
  12. Query Object relationships via Metafields

    When querying a single Object relationship metafield, you must use the target Object's id, not its slug.
    const query = {
      type: 'posts',
      'metadata.category': 'category-object-id', // Use Object ID here
    };
    await cosmic.objects.find(query);