ButterCMS JS API Client

repository·master·Indexed 41 days ago

https://github.com/buttercms/buttercms-js

A lightweight JavaScript client for interacting with the ButterCMS API (v2), supporting both Node.js (v20+) and browser environments via the native Fetch API. It provides methods to retrieve blog posts, pages, collections, categories, tags, and authors, as well as support for RSS/Atom feeds and sitemaps. Features include preview mode, custom request timeouts, caching strategies, and fetch hooks for custom transport logic.

Tokens
3.1K
Snippets
16
Records
16
Agent score
51%

What's inside ButterCMS

  1. Initialize the ButterCMS client

    master

    To use ButterCMS, initialize the client with your API token. All resource methods return Promises, so you can use .then()/.catch() or async/await syntax.

    ES6 or TypeScript

    import Butter from "buttercms";
    const butter = Butter("your_api_token");

    CDN / Browser

    <script>
      const butter = Butter("your_api_token");
    </script>

    Example: Fetching blog posts

    async function getPosts() {
      try {
        const response = await butter.post.list({page: 1, page_size: 10});
        console.log(response);
      } catch (error) {
        console.error(error);
      }
    }
  2. Enable Preview Mode

    master

    To fetch content from preview mode (useful for staging sites or local development), pass { testMode: true } during initialization.

    const butter = Butter(
      "your butter API token", 
      { testMode: true }
    );

    Alternatively, you can use an environment variable:

    const butter = Butter(
      "your butter API token", 
      { testMode: process.env.BUTTER_PREVIEW_MODE }
    );
  3. Install the ButterCMS JS client

    master

    You can install the ButterCMS client via npm for Node.js environments (requires Node.js version 20 or greater) or include it directly in your HTML via a CDN.

    npm installation

    npm install buttercms --save

    CDN installation

    <script src="https://cdn.jsdelivr.net/npm/buttercms@3.0.3/dist/butter.min.js"></script>
  4. Configure Timeouts and Caching

    master

    You can customize the request behavior during initialization using the configuration object.

    Timeouts

    The default timeout is 3000ms. To change it:

    const butter = Butter("your_api_token", { timeout: 5000 });

    Caching

    Set the caching strategy (e.g., only-if-cached):

    const butter = Butter("your_api_token", { cache: "only-if-cached" });
    const butter = Butter(
      "your butter API token", 
      { timeout: 5000 }
    );
  5. Initialize the ButterCMS client

    master

    To use the ButterCMS JS client, instantiate it by passing your apiToken and an optional options object. You can use the default export or the named Butter export.

    Available options:

    • cache: A string for caching configuration.
    • onError: A callback function (errors: any[], params?: object) => void triggered on errors.
    • onRequest: A callback function (apiEndpoint: string, params?: object) => void triggered before a request is sent.
    • onResponse: A callback function (response: Response, params?: object) => void triggered when a response is received.
    • testMode: A boolean to enable test mode.
    • timeout: A number representing the request timeout in milliseconds.
    import Butter from 'buttercms-js';
    
    const butter = Butter('YOUR_API_TOKEN', {
      timeout: 5000,
      onError: (errors) => console.error(errors),
    });
  6. Cancel pending requests

    master

    Each resource type (e.g., post, page, category) provides a cancelRequest() method. Calling this will cancel all pending requests for that specific resource type. The cancellation will result in a rejected Promise, which should be handled in a .catch() block or a try/catch statement.

    // Cancel all pending blog post requests
    butter.post.cancelRequest();
    butter.post.cancelRequest();
  7. Retrieve Pages and Collections

    master

    ButterCMS provides methods to access Pages and Collections. Parameters should be passed as a plain JavaScript object.

    Pages

    Use butter.page to interact with page types.

    • retrieve(page_type, page_slug[, params]): Get a specific page.
    • list(page_type[, params]): List pages of a type.
    • search(query[, params]): Search for pages.
    • cancelRequest(): Cancel pending requests for the page resource.
    // Get a specific page
    const response = await butter.page.retrieve("casestudy", "acme-co");

    Collections

    Use butter.content to interact with collections.

    • retrieve(collection[, params]): Get a specific collection item.
    • cancelRequest(): Cancel pending requests for the content resource.
    // Get FAQ collection with Spanish locale
    const response = await butter.content.retrieve("faq", {locale: "es"});
    // Get page
    butter.page.retrieve("casestudy", "acme-co").then(function(resp) {
      console.log(resp)
    });
  8. Use Fetch Hooks for custom transport logic

    master

    You can intercept the request/response lifecycle by providing onRequest, onResponse, and onError hooks in the initialization configuration. This is useful for adding custom headers, implementing automatic retries, or custom caching.

    Available Hooks

    onRequest(resource, config)

    Called before a request is made. Can be async.

    • resource: The API endpoint being called.
    • config: An object containing:
      • cancelRequest: Function to cancel the request.
      • headers: The Headers object (can be modified).
      • options: Original initialization options (cache, testMode, timeout).
      • params: Query parameters (can be modified).
      • type: String identifying the resource type.
    • Note: You must return options, headers, and params from this hook.

    onResponse(response, config)

    Called after a response is received. Can be async.

    • response: A clone of the JS Fetch Response object.
    • config: Contains options, params, and type.
    • Note: This hook expects no return value.

    onError(errors, config)

    Called when an error occurs. This is not an async function.

    • errors: An object containing { details: "Error details" }.
    • config: Contains options, params, and type.
    • Note: This hook expects no return value.

    Example Configuration

    const butter = Butter("your_api_token", {
      onRequest: async (resource, config) => {
        // Modify headers or params here
        return { ...config, headers: config.headers };
      },
      onResponse: async (response, config) => {
        // Handle response
      },
      onError: (errors, config) => {
        console.error("API Error:", errors.details);
      }
    });
    const butter = Butter(
      "your butter API token", 
      { 
        onError: Function,
        onRequest: Function,
        onResponse: Function
      }
    );
  9. Get Feeds (RSS, Atom, Sitemap)

    master

    The feed resource allows you to retrieve formatted feeds.

    • retrieve(feedType, params): feedType must be one of 'atom', 'rss', or 'sitemap'. You can optionally filter by category_slug or tag_slug via FeedParams.
    // Get an RSS feed for a specific category
    const rssFeed = await butter.feed.retrieve('rss', { category_slug: 'news' });
  10. Retrieve Custom Content Models

    master

    The content resource is used to fetch multiple custom content models in a single request.

    • retrieve(keys, params): Takes an array of keys corresponding to your content models. The params object supports field filtering using the fields. prefix (e.g., fields.my_field).

    To get full type safety, pass an object representing your content models to the generic retrieve method.

    interface Content1 { title: string; }
    interface Content2 { description: string; }
    
    // Retrieve both models at once
    const response = await butter.content.retrieve<{
      model_a: Content1,
      model_b: Content2
    }>(['model_a', 'model_b'], {
      'fields.title': true
    });
    
    // Data is returned as an array of objects keyed by the model name
    console.log(response.data.model_a);
  11. Cancel an ongoing request

    master

    Every resource method group (e.g., post, page, content) inherits from Methods, which includes the cancelRequest() function. Calling this will abort the ongoing fetch request associated with the current client instance via its internal AbortController.

    // Example: canceling a request
    butter.post.list().catch(err => {
      if (err.name === 'AbortError') {
        console.log('Request was canceled');
      }
    });
    
    butter.cancelRequest();
  12. Retrieve Categories, Tags, and Authors

    master

    Use these methods to fetch taxonomy and metadata:

    • category.list(params) / category.retrieve(slug, params)
    • tag.list(params) / tag.retrieve(slug, params)
    • author.list(params) / author.retrieve(slug, params)

    All these methods support an include: 'recent_posts' parameter, which returns the 10 most recent posts associated with that category, tag, or author.

    // Get a category and its 10 most recent posts
    const category = await butter.category.retrieve('tech', { include: 'recent_posts' });