{"id":15977,"library":"buttercms","title":"ButterCMS JavaScript Client","description":"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.","status":"active","version":"3.0.3","language":"javascript","source_language":"en","source_url":"git://github.com/buttercms/buttercms-js","tags":["javascript","buttercms","butter","cms","api","headless cms","typescript"],"install":[{"cmd":"npm install buttercms","lang":"bash","label":"npm"},{"cmd":"yarn add buttercms","lang":"bash","label":"yarn"},{"cmd":"pnpm add buttercms","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v3.0.0, the package is primarily designed for ES Modules. Using `require()` will likely lead to errors in ES Module contexts.","wrong":"const Butter = require('buttercms');","symbol":"Butter","correct":"import Butter from 'buttercms';"},{"note":"When included via CDN, the `Butter` object is available globally in the browser.","symbol":"Butter (browser global)","correct":"<script src=\"https://cdn.jsdelivr.net/npm/buttercms@3.0.3/dist/butter.min.js\"></script>\n<script>\n  const butter = Butter(\"your_api_token\");\n</script>"},{"note":"The main `Butter` function is a default export. `ButterClient` is a type definition for the client instance, useful for explicit type annotations in TypeScript.","wrong":"import { Butter } from 'buttercms'; // Incorrect named import for the default export","symbol":"ButterClient","correct":"import Butter, { ButterClient } from 'buttercms';\nconst butter: ButterClient = Butter(apiToken);"}],"quickstart":{"code":"import Butter from \"buttercms\";\n\n// Initialize ButterCMS client with your API token.\n// It's highly recommended to use environment variables for API tokens.\nconst BUTTER_API_TOKEN = process.env.BUTTER_API_TOKEN ?? 'YOUR_SECRET_API_TOKEN_HERE';\nconst butter = Butter(BUTTER_API_TOKEN, {\n  // Enable testMode for previewing unpublished content in development or staging.\n  testMode: process.env.NODE_ENV === 'development' || process.env.BUTTER_PREVIEW_MODE === 'true'\n});\n\nasync function fetchButterCMSContent() {\n  try {\n    // Fetch a list of blog posts\n    const postsResponse = await butter.post.list({ page: 1, page_size: 5 });\n    console.log(\"Latest Blog Posts:\", postsResponse.data.data.map(p => p.title));\n\n    // Fetch a specific page by type and slug, e.g., 'about-us' page with slug 'company-overview'\n    const pageResponse = await butter.page.retrieve(\"about-us\", \"company-overview\");\n    console.log(`Page 'about-us/company-overview' SEO Title:`, pageResponse.data.data.seo.title);\n\n    // Fetch content from a collection, e.g., 'faq' collection\n    const collectionResponse = await butter.content.retrieve(['faq'], { locale: 'en' });\n    console.log(`First FAQ item from 'faq' collection:`, collectionResponse.data.data.faq[0].question);\n\n  } catch (error) {\n    console.error(\"Failed to fetch ButterCMS content:\", error);\n    if (error instanceof Error) {\n        console.error(\"Error details:\", error.message);\n    }\n  }\n}\n\nfetchButterCMSContent();","lang":"typescript","description":"This quickstart initializes the ButterCMS client and demonstrates fetching blog posts, a specific page, and content from a collection using async/await."},"warnings":[{"fix":"Ensure your project's Node.js environment is version 20.18.0 or higher. Update `engines` in `package.json` and your CI/CD pipelines accordingly.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Remove dependencies on external `fetch` polyfills or libraries like Axios. Review and update any custom HTTP request logic that relied on the previous client implementation to use native `fetch` patterns or the library's provided methods.","message":"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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Upgrade to ButterCMS-JS version 3.x.x, ensuring your Node.js environment meets the v20 requirement.","message":"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.","severity":"deprecated","affected_versions":"<3.0.0"},{"fix":"Ensure your project is configured for ES Modules (e.g., `\"type\": \"module\"` in `package.json`) and use `import Butter from 'buttercms';`. If you must use CommonJS, you might need to use dynamic imports or a transpilation step.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Initialize the client with `const butter = Butter(\"your_api_token\", { testMode: true });` or use an environment variable like `process.env.BUTTER_PREVIEW_MODE` to control it dynamically.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Change 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.","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'.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Verify 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`).","cause":"The API token provided during client initialization is either missing, incorrect, or expired.","error":"Error: Invalid API Token"},{"fix":"Double-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`).","cause":"The `butter` client instance was not initialized correctly, or the API call chain (e.g., `post.list`) is incorrect.","error":"TypeError: butter.post.list is not a function"}],"ecosystem":"npm"}