### XML Sitemap Request Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Example of an HTTP GET request to retrieve the XML sitemap.
```http
GET https://api.buttercms.com/v2/feeds/sitemap/?auth_token=token
```
--------------------------------
### Install ButterCMS JS Client
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Install the ButterCMS JavaScript client using npm. Requires Node.js version 20 or greater.
```bash
npm install buttercms --save
```
--------------------------------
### Search Posts Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Allows searching for posts based on a query string. Supports pagination for search results.
```http
GET https://api.buttercms.com/v2/posts/search/?auth_token=token&query=javascript&page=1&page_size=10
```
```json
{
"meta": {
"count": 42,
"next_page": 2,
"previous_page": null
},
"data": [
{
"... post object ..."
}
]
}
```
--------------------------------
### Instantiate ButterCMS Client
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/module-structure.md
Create a configuration object, map resources with the config, and return an instance with all available resources. This is the primary way to start using the SDK.
```javascript
// Step 1: Create config object
const config = {
apiToken: token,
cache: options.cache || "default",
onError: options.onError || null,
onRequest: options.onRequest || null,
onResponse: options.onResponse || null,
testMode: options.testMode || false,
timeout: options.timeout || 3000,
}
// Step 2: Map each resource with config
const resources = mapResources(
{ Post, Category, Content, Feed, Page, Post, Tag },
config
)
// Step 3: Return instance with resources
return {
version: "2.0.0",
...resources // { post, category, content, feed, page, tag }
}
```
--------------------------------
### Retrieve a Page (Async/Await)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Retrieve a specific page by its type and slug. This example uses async/await syntax.
```javascript
async function getPage() {
try {
const response = await butter.page.retrieve("casestudy", "acme-co");
console.log(response);
} catch (error) {
console.error(error);
}
}
```
--------------------------------
### Development Setup with Preview Mode
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/configuration.md
Configure the SDK for development by enabling testMode and setting a custom timeout. Test mode allows for previewing unpublished content.
```javascript
const butter = Butter('your_api_token', {
testMode: true,
timeout: 5000
});
```
--------------------------------
### Interact with ButterCMS Resources
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/README.md
Examples demonstrating how to retrieve, list, and search various resources like posts, pages, and content using the initialized ButterCMS client.
```javascript
// Get posts
const response = await butter.post.list({
page: 1,
page_size: 10,
category_slug: 'news'
});
// Retrieve single page
const page = await butter.page.retrieve('landing_page', 'homepage');
// Search content
const results = await butter.post.search('javascript');
```
--------------------------------
### Fetch Blog Posts (Async/Await)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Retrieve a list of blog posts using the ButterCMS client. This example demonstrates using async/await syntax with try/catch blocks.
```javascript
async function getPosts() {
try {
const response = await butter.post.list({page: 1, page_size: 10});
console.log(response);
} catch (error) {
console.error(error);
}
}
```
--------------------------------
### Initialize ButterCMS SDK
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Content.md
Initialize the ButterCMS SDK with your API token to start making requests.
```javascript
const butter = Butter('your_api_token');
const faqContent = await butter.content.retrieve(['faq']);
```
--------------------------------
### Production Setup with Error Monitoring
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/configuration.md
Configure the SDK for production with caching enabled and a custom onError hook to send errors to a monitoring service like Sentry.
```javascript
const butter = Butter('your_api_token', {
cache: 'default',
timeout: 3000,
onError: (errors, config) => {
// Send to error tracking service
Sentry.captureException(new Error(JSON.stringify(errors)), {
tags: {
endpoint: config.type
},
extra: {
params: config.params
}
});
}
});
```
--------------------------------
### Retrieve Single Post Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Use this endpoint to fetch a specific blog post by its slug. The 'preview' parameter can be used to include draft posts.
```http
GET https://api.buttercms.com/v2/posts/my-first-post/?auth_token=token&preview=1
```
```json
{
"meta": {
"next_post": null,
"previous_post": null
},
"data": {
"author": {
"first_name": "string",
"last_name": "string",
"email": "string",
"slug": "string",
"bio": "string",
"title": "string",
"linkedin_url": "string",
"facebook_url": "string",
"pinterest_url": "string",
"instagram_url": "string",
"twitter_handle": "string",
"profile_image": "string"
},
"body": "string",
"categories": [
{
"name": "string",
"slug": "string"
}
],
"created": "2024-01-15T10:00:00Z",
"featured_image": "string | null",
"featured_image_alt": "string",
"meta_description": "string",
"published": "2024-01-15T10:00:00Z | null",
"scheduled": "2024-01-20T10:00:00Z | null",
"seo_title": "string",
"slug": "string",
"status": "published | draft | scheduled",
"summary": "string",
"tags": [
{
"name": "string",
"slug": "string"
}
],
"title": "string",
"updated": "2024-01-16T10:00:00Z | null",
"url": "string"
}
}
```
--------------------------------
### XML Sitemap Response Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Example XML structure for an XML sitemap response.
```xml
https://example.com/post-slug2024-01-15T10:00:00Z
```
--------------------------------
### RSS Feed Request Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Example of an HTTP GET request to retrieve the RSS feed with a specific tag.
```http
GET https://api.buttercms.com/v2/feeds/rss/?auth_token=token&tag_slug=javascript
```
--------------------------------
### Retrieve a Page (Promise)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Retrieve a specific page by its type and slug. This example uses Promises.
```javascript
// Get page
butter.page.retrieve("casestudy", "acme-co").then(function(resp) {
console.log(resp)
});
```
--------------------------------
### Fetch Blog Posts (Promise)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Retrieve a list of blog posts using the ButterCMS client. This example demonstrates using Promises with .then() and .catch().
```javascript
// Get blog posts
butter.post.list({page: 1, page_size: 10})
.then(function(response) {
console.log(response)
})
.catch(function(error) {
console.error(error)
})
```
--------------------------------
### Request Flow Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/module-structure.md
Illustrates the sequence of function calls and operations during an API request, from user invocation to promise resolution or rejection. Shows how utility functions like useOnRequest and useOnResponse are integrated.
```javascript
User calls: butter.post.list()
↓
Post.js wrapper calls: useButter("post", config)
↓
useButter.js list() calls: get(BASE_PATH, options)
↓
get() calls: useOnRequest(endpoint, auth_token, kwargs)
↓
useOnRequest() calls: user's onRequest hook (if exists)
↓
useOnRequest() merges config/headers/params and returns
↓
get() calls: fetch(url, { headers, signal, cache, ... })
↓
[Network request to API]
↓
get() receives response:
- If status === 200:
- get() calls: useOnResponse(response, kwargs)
- useOnResponse() calls: user's onResponse hook (if exists)
- Returns parsed JSON to user
- If status !== 200:
- get() throws error with response
- catch block parses error JSON
- catch block calls: useOnError(errors, cause)
- catch block calls: user's onError hook (if exists)
- Rejects promise with formatted Error
↓
User's Promise resolves or rejects
```
--------------------------------
### Retrieve Collection Content (Async/Await)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Retrieve content from a specific collection, optionally with locale parameters. This example uses async/await syntax.
```javascript
async function getFAQ() {
try {
const response = await butter.content.retrieve("faq", {locale: "es"});
console.log(response);
} catch (error) {
console.error(error);
}
}
```
--------------------------------
### RSS Feed Response Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Example XML structure for an RSS feed response.
```xml
Blog Feed
https://example.com
Post Title
https://example.com/post-slug
Mon, 15 Jan 2024 10:00:00 GMTPost summary
```
--------------------------------
### Fetch All Pages
Source: https://github.com/buttercms/buttercms-js/blob/master/examples/hooks.html
Retrieves all available pages from ButterCMS. This is a simple example demonstrating basic page retrieval.
```javascript
butter.page.list("*")
.then( (res) => console.log(res) )
.catch( (err) => console.error("page: ", err.message, err.cause)
)
```
--------------------------------
### List Posts Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/endpoints.md
Fetches a list of blog posts. Supports pagination and filtering by author, category, or tag. The 'exclude_body' parameter can omit post content for lighter responses.
```http
GET https://api.buttercms.com/v2/posts/?auth_token=token&page=1&page_size=10
```
```json
{
"meta": {
"count": 150,
"next_page": 2,
"previous_page": null
},
"data": [
{
"author": { ... },
"body": "string",
"categories": [ ... ],
"created": "string",
"featured_image": "string | null",
"featured_image_alt": "string",
"meta_description": "string",
"published": "string | null",
"scheduled": "string | null",
"seo_title": "string",
"slug": "string",
"status": "published | draft | scheduled",
"summary": "string",
"tags": [ ... ],
"title": "string",
"updated": "string | null",
"url": "string"
}
]
}
```
--------------------------------
### Resource Factory Pattern Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/module-structure.md
Demonstrates the factory pattern used for resource modules in the ButterCMS client. Each resource module exports a factory function that returns an object with methods for interacting with that resource.
```javascript
// Example: Post.js
export default function Post(config = {}) {
const {
cancelRequest,
list,
retrieve,
search
} = useButter("post", config);
return { cancelRequest, list, retrieve, search };
}
```
--------------------------------
### Retrieve Collection Content (Promise)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Retrieve content from a specific collection, optionally with locale parameters. This example uses Promises.
```javascript
// Get FAQ
butter.content.retrieve("faq", {locale: "es"}).then(function(resp) {
console.log(resp)
});
```
--------------------------------
### TypeScript Branded Types Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/module-structure.md
Illustrates the use of helper types in TypeScript for parameter definitions, enabling IDE autocompletion for features like flattened fields and ordered content.
```typescript
// Flattens nested fields with "fields." prefix
type WithFieldsPrefix
// Creates order parameters with "-" prefix support
type OrderParam
// Creates arrays of content items
type ContentArrays
```
--------------------------------
### Configuring Request Timeout
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/errors.md
This example demonstrates how to set a custom timeout duration (in milliseconds) for API requests when initializing the ButterCMS client.
```javascript
const butter = Butter('token', { timeout: 5000 });
```
--------------------------------
### TypeScript Generic Types Example
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/module-structure.md
Demonstrates the use of TypeScript generics for flexible type definitions, allowing for customizable types for authors, page models, and content collections.
```typescript
// Posts can have any author slug type
Post
// Pages support arbitrary field models
Page
// Content supports multiple collection types
retrieve
```
--------------------------------
### Define and Use Typed Page Models
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
This TypeScript example demonstrates how to define interfaces for specific page types, like `LandingPageModel`. This allows you to retrieve pages with full type checking on their fields, ensuring correct data access.
```typescript
// Define page types
interface LandingPageModel {
headline: string;
subheadline: string;
cta_text: string;
hero_image: string;
}
interface BlogIndexPageModel {
title: string;
description: string;
}
// Use with full type checking
async function getHomepage() {
const response = await butter.page.retrieve<
LandingPageModel,
'landing_page',
'homepage'
>('landing_page', 'homepage');
// response.data.fields is typed as LandingPageModel
const cta: string = response.data.fields.cta_text;
}
```
--------------------------------
### Define and Use Strongly Typed Content Models
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
This TypeScript example shows how to define interfaces for your ButterCMS content models, such as `FAQContent` and `TestimonialContent`. This enables full type safety when retrieving and working with content, preventing runtime errors.
```typescript
// Define your content model
interface FAQContent {
question: string;
answer: string;
category: string;
}
interface TestimonialContent {
client_name: string;
text: string;
rating: number;
approved: boolean;
}
interface MyContentCollections {
faq: FAQContent;
testimonials: TestimonialContent;
}
// Use with full type safety
async function getApprovedTestimonials() {
const response = await butter.content.retrieve(
['testimonials'],
{ 'fields.approved': true }
);
// response.data.testimonials is strongly typed
response.data.testimonials.forEach(item => {
console.log(`${item.client_name}: ${item.rating}/5`); // Type checked
});
}
```
--------------------------------
### onRequest Hook Example
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
The onRequest hook is called before an API request is made. It receives the resource and configuration, allowing modification of headers, parameters, and cancellation of the request. It must return options, headers, and params.
```javascript
onRequest(resource, config)
`resource` - The resource is the Butter API endpoint to be called
`config` - This is the configuration object that will be used to make the request
`config` includes:
`cancelRequest` - A function that can be called to cancel the request in the hook
`headers` - The headers that will be sent with the request. This is in the JS `Headers` API format. Users are able to modify these headers in the hook.
`options` - Options are the original config options set when initializing the Butter instance. This includes the `cache`, `testMode`, `timeout`. Hook functions are not included in this object.
`params` - The query parameters that will be sent with the request. Users are able to modify these parameters in the hook.
`type` - The type of resource api that is being requested. This string helps the developer to differentiate what resource is being called in the global hook.
`options`, `headers`, and `params` are to be returned by the onRequest hook for further processing and request.
```
--------------------------------
### Handling 400 Bad Request Errors
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/errors.md
This example illustrates how to catch a 400 Bad Request error, typically caused by invalid request parameters like incorrect types or values. It logs the HTTP status code.
```javascript
try {
await butter.post.list({ page_size: -1 });
} catch (error) {
console.log(error.cause.status);
}
```
--------------------------------
### Configure Multi-Environment Settings
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
Set up different configurations for development, staging, and production environments. This allows for tailored settings like timeouts and caching strategies based on the deployment environment.
```javascript
const environments = {
development: {
timeout: 10000,
testMode: true,
cache: 'no-store'
},
staging: {
timeout: 5000,
testMode: true,
cache: 'default'
},
production: {
timeout: 3000,
testMode: false,
cache: 'force-cache'
}
};
const env = process.env.NODE_ENV || 'development';
const config = environments[env];
const butter = Butter(
process.env.BUTTER_API_TOKEN,
config
);
```
--------------------------------
### Server-Side Rendering Blog Posts with Next.js
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
Fetch blog posts on the server using `getStaticProps` for initial rendering in Next.js. This improves SEO and initial load performance.
```javascript
// pages/blog/index.js
import Butter from 'buttercms';
const butter = Butter(process.env.BUTTER_API_TOKEN);
export default function BlogIndex({ posts }) {
return (
{posts.map(post => (
{post.title}
{post.summary}
))}
);
}
export async function getStaticProps() {
try {
const response = await butter.post.list({
page_size: 20
});
return {
props: {
posts: response.data
},
revalidate: 3600 // Revalidate every hour
};
} catch (error) {
console.error('Failed to fetch posts:', error);
return {
notFound: true,
revalidate: 60 // Retry after 1 minute
};
}
}
```
--------------------------------
### Configure Test Mode with Environment Variable
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/configuration.md
Dynamically set testMode based on an environment variable, allowing for flexible preview mode configuration across different deployment stages.
```javascript
const butter = Butter('token', {
testMode: process.env.BUTTER_PREVIEW_MODE === 'true'
});
```
--------------------------------
### Static Site Generation with Build-Time Fetching
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
Fetch content from ButterCMS at build time to generate static HTML files for each post and an RSS feed. This approach is suitable for static site generators.
```javascript
// build-site.js
import Butter from 'buttercms';
import fs from 'fs';
import path from 'path';
const butter = Butter(process.env.BUTTER_API_TOKEN);
async function generateSite() {
// Fetch all posts
const postsResponse = await butter.post.list({
page_size: 100
});
// Generate HTML for each post
for (const post of postsResponse.data) {
const html = generatePostHTML(post);
const filepath = path.join(
'public',
`${post.slug}.html`
);
fs.writeFileSync(filepath, html);
}
// Generate feed
const feedResponse = await butter.feed.retrieve('rss');
fs.writeFileSync('public/feed.rss', feedResponse.data);
console.log('Site generated successfully');
}
generateSite().catch(console.error);
```
--------------------------------
### Initialize ButterCMS Client
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/module-structure.md
The main entry point for creating a ButterCMS client instance. Pass your API token to the Butter factory function.
```javascript
import Butter from 'buttercms';
const butter = Butter('token'); // Returns configured instance
```
--------------------------------
### Include ButterCMS JS via CDN
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Include the ButterCMS JavaScript client directly in your HTML using a CDN link. This example shows version 3.0.3.
```html
```
--------------------------------
### Initialize ButterCMS with Preview Mode
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Initialize the ButterCMS client in preview mode for staging or local development. This can be done by passing `{ testMode: true }` or using an environment variable.
```javascript
const butter = Butter(
"your butter API token",
{ testMode: true }
);
```
```javascript
const butter = Butter(
"your butter API token",
{ testMode: process.env.BUTTER_PREVIEW_MODE }
);
```
--------------------------------
### Access ButterCMS Resources
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Butter.md
Demonstrates how to access different content resources like posts and pages after initializing the Butter client. Ensure the client is properly initialized before use.
```javascript
// Access resources
const posts = await butter.post.list();
const pages = await butter.page.retrieve('landing_page', 'homepage');
```
--------------------------------
### Load Multiple Resources in Parallel
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
This function demonstrates how to fetch multiple resources concurrently using `Promise.all`. It's useful for loading all necessary data for a page, such as blog posts, categories, and authors, in a single operation.
```javascript
// Fetch multiple resources in parallel
async function loadBlogPage() {
try {
const [
postsResponse,
categoriesResponse,
authorsResponse
] = await Promise.all([
butter.post.list({ page_size: 10 }),
butter.category.list(),
butter.author.list()
]);
return {
posts: postsResponse.data,
categories: categoriesResponse.data,
authors: authorsResponse.data
};
} catch (error) {
console.error('Failed to load page:', error);
throw error;
}
}
```
--------------------------------
### onError Hook Example
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
The onError hook is triggered when an error occurs during an API request or from the API itself. It receives the errors and configuration. This hook is not asynchronous and expects no return values.
```javascript
onError (errors, config)
`errors` - the errors returned from the API and/or the fetch request. Comes in the following object format:
```
{
details: "Error details",
}
```
`config` includes:
`options` - Options are the original config options set when initializing the Butter instance. This includes the `cache`, `testMode`, `timeout`. Hook functions are not included in this object.
`params` - The query parameters were sent with the request.
`type` - The type of resource api that was requested. This string helps the developer to differentiate what resource was called in the global hook.
`onError` expects no return values.
```
--------------------------------
### Initialize ButterCMS Client
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/configuration.md
Basic initialization of the ButterCMS client with an API token and configuration options.
```javascript
const butter = Butter(apiToken, options);
```
--------------------------------
### onResponse Hook Example
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
The onResponse hook is executed after an API response is received. It receives the response and configuration, allowing for post-processing of the response data. This hook does not expect any return values.
```javascript
onResponse (response, config)
`response` - The response object that was received from the API. This is in the JS `Fetch Response` API format and is a clone of the original response object. This will allow the user to parse the response to get the data they need whether it be JSON, text, blob, etc. The original response will be returned as JSON to the resource function call's promise resolution.
`config` - This is the configuration object that was used to make the request
`config` includes:
`options` - Options are the original config options set when initializing the Butter instance. This includes the `cache`, `testMode`, `timeout`. Hook functions are not included in this object.
`params` - The query parameters were sent with the request.
`type` - The type of resource api that was requested. This string helps the developer to differentiate what resource was called in the global hook.
`onResponse` expects no return values.
```
--------------------------------
### Initialize Butter Client with Custom Configuration
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Butter.md
Initialize the ButterCMS client with custom options like timeout, cache mode, and test mode. Useful for performance tuning or testing.
```javascript
import Butter from 'buttercms';
// With custom configuration
const butter = Butter('your_api_token', {
timeout: 5000,
cache: 'force-cache',
testMode: true
});
```
--------------------------------
### Initialize Butter Client
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Butter.md
Basic initialization of the ButterCMS client with your API token. Use this for standard API access.
```javascript
import Butter from 'buttercms';
// Basic initialization
const butter = Butter('your_api_token');
```
--------------------------------
### Cancel Post Requests
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Post.md
Aborts any currently pending requests related to post operations. This is useful for cancelling requests that are no longer needed, for example, if a user navigates away from a page before the data has loaded.
```APIDOC
## cancelRequest
### Description
Aborts any pending post requests.
### Method
`cancelRequest()`
### Signature
`cancelRequest(): void`
### Example
```javascript
// Start a list request
const listPromise = butter.post.list();
// Cancel it
butter.post.cancelRequest();
// The promise will reject with an AbortError
listPromise.catch(error => {
console.log('Request was cancelled');
});
```
```
--------------------------------
### Handling 404 Not Found Errors
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/errors.md
This example shows how to catch a 404 error when a requested ButterCMS resource, such as a post or page, does not exist. It logs the error message and the specific HTTP status code and text.
```javascript
try {
await butter.post.retrieve('non-existent-slug');
} catch (error) {
console.log(error.message);
console.log(error.cause.status);
console.log(error.cause.statusText);
}
```
--------------------------------
### Initialize ButterCMS Client
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/README.md
Instantiate the ButterCMS client with your API token and optional configuration settings like timeouts, cache modes, and request/response/error hooks.
```javascript
import Butter from 'buttercms';
const butter = Butter('your_api_token', {
timeout: 3000,
testMode: false,
cache: 'default',
onRequest: async (endpoint, config) => ({ headers, options, params }),
onResponse: async (response, config) => {},
onError: (errors, config) => {}
});
```
--------------------------------
### Enable Test Mode
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/configuration.md
Enable preview and test API endpoints by setting testMode to true. This adds 'test=1' and 'preview=1' query parameters to requests, useful for local development and staging.
```javascript
const butter = Butter('token', {
testMode: true
});
```
--------------------------------
### Initialize ButterCMS with Fetch Hooks
Source: https://github.com/buttercms/buttercms-js/blob/master/examples/hooks.html
Initializes the ButterCMS SDK with custom fetch hooks for request and response handling. The `onRequest` hook allows for request cancellation, while `onResponse` can process the response body.
```javascript
const butter = Butter( 'your_buttercms_api_token_here', {
onError (error, config) {
console.log("on Error for: ", config.type, error, config)
},
async onRequest (resource, config) {
console.log("requestHook", config.type, resource, config)
config.type === "page" && await config.cancelRequest()
return config
},
async onResponse (response, config) {
console.log("responseHook", config.type, response, config)
console.log(await response.text())
return
}
} );
```
--------------------------------
### Paginate Through Content
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Content.md
Retrieves the second page ('page': 2) of the 'testimonials' collection, with each page containing 20 items ('page_size': 20).
```javascript
// Paginate through content
const secondPage = await butter.content.retrieve(
['testimonials'],
{ page: 2, page_size: 20 }
);
```
--------------------------------
### Implement Service Worker Caching
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
This example shows how to implement caching for ButterCMS API requests within a browser Service Worker. It intercepts fetch events, caches successful responses, and serves cached data when the network is unavailable.
```javascript
// In service worker
self.addEventListener('fetch', event => {
if (event.request.url.includes('api.buttercms.com')) {
event.respondWith(
caches.open('buttercms-cache').then(cache => {
return fetch(event.request)
.then(response => {
// Cache successful responses
cache.put(event.request, response.clone());
return response;
})
.catch(() => {
// Return cached response on network error
return cache.match(event.request);
});
})
);
}
});
```
--------------------------------
### Mocking ButterCMS SDK for Unit Tests
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
Mock the ButterCMS SDK using Jest to isolate components and test their interactions with the SDK without making actual API calls. This setup is useful for testing data fetching logic.
```javascript
// jest.setup.js
import Butter from 'buttercms';
// Mock Butter for tests
jest.mock('buttercms', () => {
return jest.fn(() => ({
post: {
list: jest.fn(),
retrieve: jest.fn(),
search: jest.fn(),
cancelRequest: jest.fn()
},
page: {
list: jest.fn(),
retrieve: jest.fn(),
search: jest.fn(),
cancelRequest: jest.fn()
},
// ... other resources
}));
});
// In tests
test('loads posts on mount', async () => {
const mockButter = Butter();
mockButter.post.list.mockResolvedValue({
data: [
{ slug: 'post-1', title: 'Post 1' },
{ slug: 'post-2', title: 'Post 2' }
]
});
const { getByText } = render();
await waitFor(() => {
expect(getByText('Post 1')).toBeInTheDocument();
});
});
```
--------------------------------
### Configure ButterCMS Client with Environment Variables
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/configuration.md
Initialize the ButterCMS client using environment variables for sensitive information like API tokens and configuration settings such as preview mode, timeout, and cache.
```javascript
const butter = Butter(
process.env.BUTTER_API_TOKEN,
{
testMode: process.env.BUTTER_PREVIEW_MODE === 'true',
timeout: parseInt(process.env.BUTTER_TIMEOUT) || 3000,
cache: process.env.BUTTER_CACHE || 'default'
}
);
```
--------------------------------
### Retrieve Multiple Content Collections with TypeScript Interfaces
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Content.md
Demonstrates retrieving multiple content collections ('faq' and 'testimonials') using TypeScript interfaces for type safety and structured access to data.
```typescript
interface FAQItem {
question: string;
answer: string;
category: string;
}
interface TestimonialItem {
client_name: string;
text: string;
rating: number;
}
interface ContentCollections {
faq: FAQItem;
testimonials: TestimonialItem;
}
const response = await butter.content.retrieve(
['faq', 'testimonials']
);
// Access items from each collection
response.data.faq.forEach(item => {
console.log(`${item.question} - ${item.category}`);
});
response.data.testimonials.forEach(item => {
console.log(`${item.client_name}: ${item.rating}/5`);
});
```
--------------------------------
### Retrieve a Single Page
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Page.md
Fetches a specific page by its type and slug. Use this when you know the exact page you need to display.
```javascript
const page = await butter.page.retrieve('landing_page', 'homepage');
```
--------------------------------
### Order Content by Field
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Content.md
Fetches the 'faq' collection, ordering the results by the 'created' field in descending order (newest first).
```typescript
// Order by field (descending date)
const recentFAQ = await butter.content.retrieve(
['faq'],
{ order: '-created' }
);
```
--------------------------------
### Static Generation with Incremental Static Regeneration (ISR) in Next.js
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/advanced-usage.md
Implement dynamic routing for individual blog posts using `getStaticPaths` and `getStaticProps` in Next.js. This enables on-demand generation and regeneration of pages.
```javascript
// pages/blog/[slug].js
export async function getStaticPaths() {
const response = await butter.post.list({ page_size: 100 });
const paths = response.data.map(post => ({
params: { slug: post.slug }
}));
return {
paths,
fallback: 'blocking' // Generate new paths on demand
};
}
export async function getStaticProps({ params }) {
try {
const response = await butter.post.retrieve(params.slug);
return {
props: {
post: response.data
},
revalidate: 3600
};
} catch (error) {
return {
notFound: true,
revalidate: 300
};
}
}
```
--------------------------------
### Retrieve Content with Localization
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Content.md
Fetches the 'faq' collection specifically for the Spanish locale ('es').
```javascript
// Retrieve with localization
const spanishFAQ = await butter.content.retrieve(
['faq'],
{ locale: 'es' }
);
```
--------------------------------
### Initialize ButterCMS Client
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Category.md
Initialize the ButterCMS client with your API token. This is a prerequisite for making any API calls.
```javascript
const butter = Butter('your_api_token');
```
--------------------------------
### Initialize ButterCMS Client (ES6/TypeScript)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Initialize the ButterCMS client instance using your API token. This is the standard method for ES6 or TypeScript projects.
```javascript
import Butter from "buttercms";
const butter = Butter("your_api_token");
```
--------------------------------
### Initialize Butter Client with Request/Response Hooks
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Butter.md
Initialize the ButterCMS client with hooks to intercept and handle API requests and responses. This is useful for logging, debugging, or modifying requests/responses.
```javascript
import Butter from 'buttercms';
// With hooks for request/response handling
const butter = Butter('your_api_token', {
onRequest: async (endpoint, config) => {
console.log(`Making request to ${endpoint}`);
// Modify headers or params if needed
return {
headers: config.headers,
options: config.options,
params: config.params
};
},
onResponse: async (response, config) => {
console.log(`Received response with status ${response.status}`);
},
onError: (errors, config) => {
console.error('API Error:', errors);
}
});
```
--------------------------------
### Initialize ButterCMS Client (CDN)
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Initialize the ButterCMS client instance using your API token when included via CDN. This method is used within HTML script tags.
```javascript
const butter = Butter("your_api_token");
```
--------------------------------
### List All Tags
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Tag.md
Retrieves a list of all available tags in the system. Useful for displaying tag clouds or navigation.
```javascript
// List all tags
const response = await butter.tag.list();
console.log(`Found ${response.data.length} tags`);
response.data.forEach(tag => {
console.log(`- ${tag.name}`);
});
```
--------------------------------
### Initialize Butter SDK with Hooks
Source: https://github.com/buttercms/buttercms-js/blob/master/README.md
Configure the Butter SDK with custom hook functions for request handling, response processing, and error management. These hooks can be declared as async functions for asynchronous operations.
```javascript
const butter = Butter(
"your butter API token",
{
onError: Function,
onRequest: Function,
onResponse: Function
}
);
```
--------------------------------
### Generate Static Atom, RSS, and Sitemap Files
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Feed.md
This script generates static feed files (Atom, RSS, Sitemap) and saves them to the './public' directory. It iterates through feed types and writes the retrieved data to corresponding files.
```javascript
import fs from 'fs';
import path from 'path';
import Butter from 'buttercms';
const butter = Butter('your_api_token');
async function generateFeeds() {
const feedTypes = ['atom', 'rss', 'sitemap'];
for (const feedType of feedTypes) {
const response = await butter.feed.retrieve(feedType);
const filename = `feed.${feedType === 'sitemap' ? 'xml' : feedType}`;
const filepath = path.join('./public', filename);
fs.writeFileSync(filepath, response.data);
console.log(`Generated ${filepath}`);
}
}
generateFeeds().catch(console.error);
```
--------------------------------
### Create a Tag Cloud
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Tag.md
Generates an HTML string for a tag cloud from a list of tags. This is a common UI pattern for tag navigation.
```javascript
// Create a tag cloud
const tagCloud = response.data
.map(tag => `${tag.name}`)
.join(' ');
console.log(`
${tagCloud}
`);
```
--------------------------------
### Fetch and Display Blog Posts in Browser
Source: https://github.com/buttercms/buttercms-js/blob/master/examples/basic.html
This snippet fetches a list of blog posts using the ButterCMS SDK and appends their titles and URLs to an HTML element with the ID 'posts'. It also displays pagination information.
```javascript
$(function() {
const butter = Butter( 'your_buttercms_api_token_here' );
butter.post.list({ page: 1, page_size: 10 })
.then( (resp) => {
const { meta, data: posts } = resp.data;
for(i = 0; i < posts.length; i++) {
var title = posts[i].title;
$('#posts').append(
` ${ title } ${ posts[i].url } Previous Page: ${ meta.previous_page } Next Page: ${ meta.next_page } `
)
}
}
);
});
```
--------------------------------
### List All Posts with Pagination
Source: https://github.com/buttercms/buttercms-js/blob/master/_autodocs/api-reference/Post.md
Retrieves a paginated list of all blog posts, displaying the total count and iterating through the post titles and author names.
```javascript
// List all posts with pagination
const response = await butter.post.list({ page: 1, page_size: 10 });
console.log(`Found ${response.meta.count} posts`);
response.data.forEach(post => {
console.log(`${post.title} by ${post.author.first_name}`);
});
```
--------------------------------
### Fetch and Display Posts with Pagination
Source: https://github.com/buttercms/buttercms-js/blob/master/examples/hooks.html
Fetches a list of posts, paginates through them, and appends their titles and URLs to an HTML element. It also displays pagination information.
```javascript
butter.post.list({ page: 1, page_size: 10 })
.then( (resp) => {
const { meta, data: posts } = resp.data
if (!posts) return
for(i = 0; i < posts.length; i++) {
var title = posts[i].title;
$('#posts').append(
` ${ title } ${ posts[i].url } Previous Page: ${ meta.previous_page } Next Page: ${ meta.next_page } `
)
}
})
.catch( (err) => console.error("post: ", err.message, err.cause)
);
```
--------------------------------
### List Blog Posts
Source: https://github.com/buttercms/buttercms-js/blob/master/tests/basic.html
This snippet demonstrates how to list blog posts with pagination and append their titles and URLs to the DOM. It also includes error handling.
```javascript
butter.post.list({ page: 1, page_size: 10 }) .then( (resp) => { const { meta, data: posts } = resp.data if (posts) { for(i = 0; i < posts.length; i++) { var title = posts[i].title; $('#posts').append(