ButterCMS JavaScript Client
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
-
ReferenceError: require is not defined in ES module scope
cause Attempting to use `require()` syntax in an ES Module context, which is the default for Node.js 20+ applications or projects explicitly configured as 'type: module'.fixChange your import statement from `const Butter = require('buttercms');` to `import Butter from 'buttercms';`. Ensure your `package.json` either has `"type": "module"` or your file uses a `.mjs` extension. -
Error: Invalid API Token
cause The API token provided during client initialization is either missing, incorrect, or expired.fixVerify that your ButterCMS API token is correct and active. Ensure it's passed as the first argument to the `Butter()` function. Avoid hardcoding tokens directly in code; use environment variables (e.g., `process.env.BUTTER_API_TOKEN`). -
TypeError: butter.post.list is not a function
cause The `butter` client instance was not initialized correctly, or the API call chain (e.g., `post.list`) is incorrect.fixDouble-check that `const butter = Butter('your_api_token');` is called correctly and returns a valid client object. Refer to the ButterCMS API documentation for the correct resource and method calls (e.g., `butter.post.list`, `butter.page.retrieve`).
Warnings
- breaking Version 3.0.0 introduced a breaking change by upgrading to Node.js 20, making it the minimum required Node.js version. Projects using older Node.js versions must upgrade.
- breaking ButterCMS-JS version 2 (and consequently v3) transitioned from third-party HTTP clients to the native `fetch` API. This is a breaking change for anyone migrating from version 1, as custom Axios configurations or interceptors might no longer work as expected.
- deprecated Support for ButterCMS-JS version 2 will end in May 2025, aligning with the Node.js v18 sunset. Users are strongly encouraged to migrate to version 3 to ensure continued support and compatibility.
- gotcha When migrating from CommonJS (`require`) to ES Modules (`import`), developers might encounter 'ReferenceError: require is not defined in ES module scope' errors or unexpected behavior due to Node.js's module resolution differences. Version 3 is ESM-first.
- gotcha To fetch unpublished or draft content, you must explicitly enable `testMode` during client initialization. Failing to do so will result in only published content being returned.
Install
-
npm install buttercms -
yarn add buttercms -
pnpm add buttercms
Imports
- Butter
const Butter = require('buttercms');import Butter from 'buttercms';
- Butter (browser global)
<script src="https://cdn.jsdelivr.net/npm/buttercms@3.0.3/dist/butter.min.js"></script> <script> const butter = Butter("your_api_token"); </script> - ButterClient
import { Butter } from 'buttercms'; // Incorrect named import for the default exportimport Butter, { ButterClient } from 'buttercms'; const butter: ButterClient = Butter(apiToken);
Quickstart
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();