> ## Documentation Index
> Fetch the complete documentation index at: https://buttercms.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Automating cross-site sync

> Use the Write API to programmatically sync content between sites and environments.

> [!NOTE]
>
> For dashboard-based migrations, see [Migrating Content](https://buttercms.com/docs/create-content/multi-site-environments/migrating-content.md).

## Automated syncing with Write API

> [!NOTE]
>
> **When to use Write API vs Migrations:**
>
> * **Migrations tool:** Best for one-time or infrequent bulk content transfers between environments. Handled by the ButterCMS support team through the dashboard.
> * **Write API:** Best for automated, programmatic, or frequent content syncing. Requires development work but gives you full control over what, when, and how content is synced.

For automated or frequent syncing, use the Write API:

### Basic sync script

```javascript theme={null}
import Butter from 'buttercms';

// Source site (read token) and destination site (write token)
const sourceButter = Butter('source-site-read-token');
const DEST_WRITE_TOKEN = 'dest-site-write-token';

// The JS SDK's Content resource is read-only, so writes to the destination
// site go directly to the Write API.
async function createCollectionItem(collectionSlug, fields) {
  const res = await fetch('https://api.buttercms.com/v2/content/', {
    method: 'POST',
    headers: {
      'Authorization': `Token ${DEST_WRITE_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ key: collectionSlug, fields: [fields] })
  });
  if (!res.ok) {
    throw new Error(`Write API ${res.status}: ${await res.text()}`);
  }
}

async function syncCollection(collectionSlug) {
  // Fetch from source
  const { data } = await sourceButter.content.retrieve(collectionSlug);
  const items = data.data[collectionSlug];

  // Push to destination. Read responses include a `meta` object per item,
  // which the Write API rejects as an unknown field.
  for (const { meta, ...fields } of items) {
    await createCollectionItem(collectionSlug, fields);
  }

  console.log(`Synced ${items.length} items to ${collectionSlug}`);
}

// Sync authors collection
syncCollection('authors');
```

### Syncing localized collections

Collection reads return one locale per request, while the Write API accepts every locale in a single item. Fetch each locale from the source, group the results by `meta.id` and nest the fields under their locale codes. Both sites must have the same locale codes configured.

```javascript theme={null}
async function syncLocalizedCollection(collectionSlug, locales) {
  const fieldsByItemId = new Map();

  for (const locale of locales) {
    const { data } = await sourceButter.content.retrieve(collectionSlug, { locale });
    for (const { meta, ...fields } of data.data[collectionSlug]) {
      const item = fieldsByItemId.get(meta.id) ?? {};
      item[locale] = fields;
      fieldsByItemId.set(meta.id, item);
    }
  }

  // Each item is posted as fields: [{ en: {...}, es: {...} }]
  for (const fieldsByLocale of fieldsByItemId.values()) {
    await createCollectionItem(collectionSlug, fieldsByLocale);
  }

  console.log(`Synced ${fieldsByItemId.size} localized items to ${collectionSlug}`);
}

syncLocalizedCollection('authors', ['en', 'es']);
```

### Scheduled sync

Set up automated syncing with cron jobs or serverless functions:

```javascript theme={null}
// AWS Lambda / Vercel Serverless Function
import Butter from 'buttercms';

// The JS SDK's Page resource is read-only (retrieve/list/search), so creating
// pages on the destination site goes directly to the Write API.
export async function handler(event) {
  const sourceButter = Butter(process.env.SOURCE_READ_TOKEN);
  // Use a page type key; '*' lists single pages, which have no page type
  // and can't be created through the Write API
  const pageType = 'landing-page';

  // Fetch recently updated content
  const { data } = await sourceButter.page.list(pageType, {
    page_size: 100,
    order: '-updated'
  });

  // Sync to destination
  for (const page of data.data) {
    const res = await fetch('https://api.buttercms.com/v2/pages/', {
      method: 'POST',
      headers: {
        'Authorization': `Token ${process.env.DEST_WRITE_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        'page-type': pageType,
        title: page.name,
        slug: page.slug,
        status: 'draft',
        fields: page.fields
      })
    });
    if (!res.ok) {
      throw new Error(`Write API ${res.status} for ${page.slug}: ${await res.text()}`);
    }
  }

  return { statusCode: 200, body: 'Sync complete' };
}
```

> [!NOTE]
>
> Write API access is a paid add-on for Advanced and Professional plans. Enable it from the Billing page in your dashboard.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.