ButterCMS JavaScript Client

3.0.3 · active · verified Tue Apr 21

The ButterCMS JavaScript Client (current stable v3.0.3) provides a robust interface for interacting with the ButterCMS Headless CMS API within Node.js and browser environments. It simplifies fetching various content types including blog posts, pages, collections, categories, tags, and authors. The library maintains a release cadence tied closely to Node.js LTS cycles, with version 3 supporting Node.js 20, and version 4 slated for Node.js 22. A key differentiator is its shift to native `fetch` API for HTTP requests since v2, reducing external dependencies and ensuring consistent behavior across modern JavaScript environments. It ships with comprehensive TypeScript types, enabling a smooth development experience with type-checking and autocompletion. Developers can utilize a preview mode for staging content before publishing.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes the ButterCMS client and demonstrates fetching blog posts, a specific page, and content from a collection using async/await.

import Butter from "buttercms";

// Initialize ButterCMS client with your API token.
// It's highly recommended to use environment variables for API tokens.
const BUTTER_API_TOKEN = process.env.BUTTER_API_TOKEN ?? 'YOUR_SECRET_API_TOKEN_HERE';
const butter = Butter(BUTTER_API_TOKEN, {
  // Enable testMode for previewing unpublished content in development or staging.
  testMode: process.env.NODE_ENV === 'development' || process.env.BUTTER_PREVIEW_MODE === 'true'
});

async function fetchButterCMSContent() {
  try {
    // Fetch a list of blog posts
    const postsResponse = await butter.post.list({ page: 1, page_size: 5 });
    console.log("Latest Blog Posts:", postsResponse.data.data.map(p => p.title));

    // Fetch a specific page by type and slug, e.g., 'about-us' page with slug 'company-overview'
    const pageResponse = await butter.page.retrieve("about-us", "company-overview");
    console.log(`Page 'about-us/company-overview' SEO Title:`, pageResponse.data.data.seo.title);

    // Fetch content from a collection, e.g., 'faq' collection
    const collectionResponse = await butter.content.retrieve(['faq'], { locale: 'en' });
    console.log(`First FAQ item from 'faq' collection:`, collectionResponse.data.data.faq[0].question);

  } catch (error) {
    console.error("Failed to fetch ButterCMS content:", error);
    if (error instanceof Error) {
        console.error("Error details:", error.message);
    }
  }
}

fetchButterCMSContent();

view raw JSON →