Run this in your commandline:

npm install buttercms --save

Butter can also be loaded using a CDN:

<script src="https://cdnjs.buttercms.com/buttercms-1.1.4.min.js"></script>

Or if you're using Yarn:

yarn add buttercms

The source code to a complete sample Next.js application is available on Github.

To test the ButterCMS API, set your API token:

var butter = require('buttercms')('your_api_token');

Or if using ES6 syntax:

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

Then run:

butter.post.list({page: 1, page_size: 10}).then(function(response) {
  console.log(response)
})

This API request fetches our blog posts. Your account comes with one example post which you'll see in the response. If you get a response it means you're now able to connect to our API.

Next, create a new directory for your app and add a package.json file:

{
  "name": "react-blog"
}

Next, install Next.js, React, and the ButterCMS API. As of the time of this writing, we'll want to install the Next.js for custom routing we'll use later:

npm install next@beta react react-dom buttercms  --save

Then add a script to your package.json:

{
  "scripts": {
    "start": "next"
  }
}

Next.js treats every js file in the ./pages directory as a page. Let's setup a basic homepage by creating a ./pages/index.js inside your project:

export default () => (
  <div>My blog homepage</div>
)

And then just run npm run start and go to http://localhost:3000

Then create a ./pages/post.js and check it out at http://localhost:3000/post

export default () => (
  <div>A blog post</div>
)
Contents

Headless CMS

ButterCMS is a headless CMS that lets you manage content using our dashboard and integrate it into your tech stack of choice with our content APIs. You can use ButterCMS for new projects as well as add it to existing codebases.

If you're familiar with Wordpress, see how ButterCMS compares to WordPress.

ButterCMS provides a user-friendly UI for managing marketing sites, blogging, and custom content scenarios. We can be used for SEO landing pages, customer case studies, company news & updates, events + webinar pages, education center, location pages, knowledgebases, and more.

We are different from a traditional CMS like Drupal or Wordpress in that we're not a large piece of software you need to download, host, customize, and maintain. Instead we provide easy to consume, performant content API's that you add to your application.

For example, if you wanted to enable a non-technical person to be able to add customer case study pages to your marketing site, you might create a Case Study Page Type to represent these pages. The non-technical person would be able to manage these pages from our dashboard and the JSON API output would look something like this:

{  
  "data": {
    "slug": "acme-co-case-study",
    "page_type": "case_study",
    "fields": {
      "seo_title": "Acme Co Customer Case Study",
      "seo_description": "Acme Co saved 200% on Anvil costs with ButterCMS",
      "title": "Acme Co loves ButterCMS",
      "body": "<p>We've been able to make anvils faster than ever before! - Chief Anvil Maker</p>"
    }
  }
}

Use Postman to experiment

Postman is a great tool for experimenting with our API. We wrote a post about it here. Once you've installed Postman, click this button to quickly add our end point Collection to your Postman.

Run in Postman

Write API

We have a Write / POST API that allows you to programmatically create content. This can enable many powerful use cases and allow you to scale your content faster than ever.

Refer to our Write API Documentation to learn more.

Our Write API is available in our Enterprise plan and you will need to use a write-enabled token which is provided on request. Just contact us via email or livechat to get yours.

Webhooks

Webhooks are a powerful feature that allow you to notify your internal systems whenever content in ButterCMS has changed. You can learn more about Webhooks in this blog post.

Reloading the Next.js app on adding a new page

We can make use of the ButterCMS webhooks to notify our application everytime a new page is added or modified, and reload the next.js application.

You can add a new webhook by going to the https://buttercms.com/webhooks/ page. There, you can provide the URL of your deployed application:

Suppose your server is deployed with the address http://abc.def/, we can create a /webhook-receiver route, so that the resulting webhook URL configured on ButterCMS would be http://abc.def/webhook-receiver. We will get a POST request everytime there is a change, so lets create the corresponding route inside server.js

server.post('/webhook-receiver', (req, res) => {
console.log('a post has been modified')
app
  .prepare()
  .then(() => {
    console.log('app refreshed')
    res.end()
  })
  .catch((e) => {
    res.status(500).end()
  })
})

The route will call the app.prepare function, which reloads the Next.js application.

Image Transformation

ButterCMS has integrated with a rich image transformation API called Filestack. This allows you to modify your uploaded images in dozens of ways. Everything from resizing, cropping, effects, filters, applying watermarks and more. Check out Filestack full documentation for more detail.

After you upload an image to ButterCMS, it's stored on our CDN. To create a thumbnail, here's an example:

Original URL = https://cdn.buttercms.com/zjypya5tRny63LqhHQrv

Thumbnail URL = https://fs.buttercms.com/resize=width:200,height:200/zjypya5tRny63LqhHQrv

Resizing is just one of the many different transformations you can do to your images. Refer to the Filestack docs for full details.

Localization

ButterCMS has full support for localization of your content. Locale names and keys are completely customizable and there's no limit to the number of locales you can have. View our API Reference to learn how to query by locale.

Roles and Permissions

To give your team maximum control over what your users can do, your ButterCMS account comes with three roles by default:

  • Admin - can do everything on an account. You'll want to use this for your developers as they deal with the content configuration that is used within your project's code.
  • Publisher - can edit, publish and delete content, but cannot manage users or configure content schemas.
  • Author - can create and edit draft content (Blog Posts, Pages, Collections) but cannot publish content live to your site.

Custom built roles are available in our Enterprise plan. Chat with us to discuss Enterprise options.

Manage Multiple Environments

ButterCMS Multisite allows you to manage multiple websites and multiple environments from one place. You can get an admin level view and quickly switch between your ButterCMS instances.

From the Environment dashboard you can quickly switch between your different ButterCMS environments. In the example below, Elon is currently logged into Production and can switch into Staging, Dev, or QA in one-click

Multiple Environments

Multiple Environments are available in our Enterprise plan. Just contact us via email or livechat to get yours.

Manage Multiple Websites

Being able to manage multiple environments is great for a large project but what about massive projects where you need to manage multiple sites AND multiple environments? For instance if you're an Enterprise with several sub-branded websites that you want to be able to manage, this allows you to do that. Continuing from the example above, let's say Elon wanted to expand using Butter beyond just Tesla to include SpaceX and The Boring Company as well.

Our dashboard easily scales to meet this need. Now when Elon visits the multisite dashboard, he will see this:

Multiple Environments

Multiple Websites and Environments are available in our Enterprise plan. Just contact us via email or livechat to get yours.

Table of Contents

Introduction

Quickly launch a new marketing site or add CMS-powered pages to your existing site using our Pages.

Create a Single Page

Adding a CMS-powered page to your app involves three easy steps:

  1. Create the Page structure
  2. Populate the content
  3. Integrate into your application

If you need help after reading this, contact us via email or livechat.

Create the Page Structure

Create a new Page and define it's structure using our Page Builder. Let's create an example homepage.

PagesNewSinglePage

Populate the Content

Then populate our new page with content. In the next step, we'll call the ButterCMS API to retrieve this content from our app.

PagesNewSinglePageContent

Integrate into your application

With your homepage defined, the ButterCMS Pages API will return it in JSON format like this:

{
  "data": {
    "slug": "homepage",
    "page_type": null,
    "fields": {
      "seo_title": "Anvils and Dynamite | Acme Co",
      "headline": "Acme Co provides supplies to your favorite cartoon heroes.",
      "hero_image": "https://cdn.buttercms.com/c8oSTGcwQDC5I58km5WV",
      "call_to_action": "Buy Now",
      "customer_logos": [
        {
          "logo_image": "https://cdn.buttercms.com/c8oSTGcwQDC5I58km5WV"
        },
        {
          "logo_image": "https://cdn.buttercms.com/c8oSTGcwQDC5I58km5WV"
        }
      ]
    }
  }
}

To integrate this into your app, update pages/index.js:

import React from 'react'
import Butter from 'buttercms'
import Head from 'next/head'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps () {
    const resp = await butter.page.retrieve('*', 'homepage')
    return resp.data
  }
  render () {
    const product = this.props.data
    const { 
      seo_title: seoTitle, 
      hero_image: heroImage, 
      call_to_action: callToAction, 
      customer_logos: customerLogos,
      headline } = product.fields

    return (
      <div>
        <Head>
          <title>{seoTitle}</title>
        </Head>

        <img src={heroImage} />
        <h1>{headline}</h1>

        <button>{callToAction}</button>
        // Loop through customer_logos
      </div>
    )
  }
}

That's it! If you browse to your homepage you'll see your homepage populated with the content you created in Butter.

Create multiple pages using Page Types

Overview Video

Let's say you want to add a set of customer case study pages to your marketing site. They all have the same structure but the content is different. Page Types are perfect for this scenario and involves three easy steps:

  1. Create the Page Type structure
  2. Populate the content
  3. Integrate into your application

If you need help after reading this, contact us via email or livechat.

Create the Page Type structure

Create a Page Type to represent your Customer Case Study pages:

PagesNewPageType1

After saving, return to the configuration page by clicking the gear icon:

PagesNewPageType2

Then click on Create Page Type and name it "Customer Case Study". This will allow us to reuse this field configuration across multiple customer case study pages:

PagesNewPageType3

Populate the Content

Then populate our new page with content. In the next step, we'll call the ButterCMS API to retrieve this content from our app.

PagesNewSinglePageContent

Integrate into your application

With a case study defined, the ButterCMS Pages API will return it in JSON format like this:

{  
  "data": {
    "slug": "acme-co-case-study",
    "page_type": "case_study",
    "fields": {
      "seo_title": "Acme Co Customer Case Study",
      "seo_description": "Acme Co saved 200% on Anvil costs with ButterCMS",
      "title": "Acme Co loves ButterCMS",
      "body": "<p>We've been able to make anvils faster than ever before! - Chief Anvil Maker</p>"
    }
  }
}

To integrate this into your app, create pages/case-study.js:

import React from 'react'
import Butter from 'buttercms'
import Head from 'next/head'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps ({ query }) {
    const resp = await butter.page.retrieve('customer_case_study', query.slug)
    return resp.data
  }
  render () {
    const product = this.props.data
    const { seo_title: seoTitle, customer_logo: customerLogo, headline, testimonial } = product.fields

    return (
      <div>
        <Head>
          <title>{seoTitle}</title>
        </Head>

        <div>
          <img src={customerLogo} />
        </div>
        <h1>{headline}</h1>
        <div dangerouslySetInnerHTML={{ __html: testimonial }} />
      </div>
    )
  }
}

Update the routes in your app to route to the specified components

Finally, we add the route for the page to server.js:

server.get('/case-studies/:slug', (req, res) => {
  return app.render(req, res, '/case-study', { slug: req.params.slug })
})

Setup the Customers Page to list all our customers

Create a new file pages/case-studies.js In this file, we should:

  1. Initialize the butterCMS library
  2. On the getInitialProps hook, fetch the list of case studies
  3. Return the response data as the component props
import React from 'react'
import Butter from 'buttercms'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps ({ query }) {
    const resp = await butter.page.list('customer_case_study')
    return resp.data
  }
  render () {
    return (
      <div>
        {this.props.data.map((caseStudy, key) => {
          return (
            <div key={key}>
              <img src={caseStudy.fields.customer_logo} />
              <a href={`/case-studies/${caseStudy.slug}`}>{caseStudy.fields.headline}</a>
            </div>
          )
        })}
      </div>
    )
  }
}

That's it! The page your created in Butter dashboard will immediately show in your app.

If you need help after reading this, contact us via email or livechat.

Introduction

Collections are tables of data to be referenced by Pages, extending the use cases that you can achieve with ButterCMS. Collections can also be queried from the API directly. We'll cover example use cases of both.

Several of these use cases involve References. References are a powerful field type you can add to Pages and Collections that allow you to create links between your content.

Use Cases

Page Facets to Group/Filter By

You can use Collections as Facets (filterable properties) for your Pages. The simpliest example would be to add Categories to your Pages. Let's say you have a recipe website for different cocktails and you want to add categories to better organize these cocktail pages for your customers.

Each cocktail Page has a name, image, and ingredients:

Sample Cocktail Page

Here's what the API JSON response looks like for your cocktail pages. You're going to enhance this by adding a Reference to a Category Collection.

GET https://api.buttercms.com/v2/pages/cocktails/

{
    "data": [
        {
            "slug": "old-fashioned",
            "fields": {
                "name": "Old Fashioned",
                "image": "https://cdn.buttercms.com/k4UHbZOuRhOMKw3Gys8s",
                "ingredients": "<p>1/2 tsp Sugar<br />3 dashes Angostura bitters<br />1 tsp Water<br />2 oz Bourbon</p>"
            }
        },
        {
            "slug": "martini",
            "fields": {
                "name": "Martini",
                "image": "https://cdn.buttercms.com/UKVn6r1RQSVyKoZIVeHU",
                "ingredients": "<p>2 oz. vodka</p>\n<p>1/2 oz. dry vermouth</p>\n<p>Shake ingredients with ice. Strain into a martini glass. Popular garnishes include a lemon twist and olives.</p>"
             }
        }
    ],
    meta": {
        "count": 2,
        "previous_page": null,
        "next_page": null
    }
}

To add a Category to your cocktail pages, first create a Category Collection and then configure your Collection data structure by adding Name and Slug properties to it.

Create Category Collection
Name Slug Properties To Collection

Now you can add some cocktail categories to it like Martini, Old Fashioned, etc...

Adding Items To Collection

With your Collection in place, go back to your Cocktail Page Type and add a Reference field called "Category" to the Category Collection

Adding Reference Field To Collection

Now when editing your cocktail pages, you can now categorize your cocktails.

Select a Category

These categories of course also show up in your API response your cocktails:

GET https://api.buttercms.com/v2/pages/cocktails/

{
    "data": [
        {
            "slug": "old-fashioned",
            "fields": {
                "name": "Old Fashioned",
                "image": "https://cdn.buttercms.com/k4UHbZOuRhOMKw3Gys8s",
                "ingredients": "<p>1/2 tsp Sugar<br />3 dashes Angostura bitters<br />1 tsp Water<br />2 oz Bourbon</p>",
                "category": {
                    "name": "Old Fashioned",
                    "slug": "old-fashioned"
                }
            }
        },
        {
            "slug": "martini",
            "fields": {
                "name": "Martini",
                "image": "https://cdn.buttercms.com/UKVn6r1RQSVyKoZIVeHU",
                "ingredients": "<p>2 oz. vodka</p>\n<p>1/2 oz. dry vermouth</p>\n<p>Shake ingredients with ice. Strain into a martini glass. Popular garnishes include a lemon twist and olives.</p>",
                "category": {
                    "name": "Martini",
                    "slug": "martini"
                }
             }
        }
    ],
    meta": {
        "count": 2,
        "previous_page": null,
        "next_page": null
    }
}

Naturally, now that your pages have categories, you'll want to filter your pages by category. To do this just add fields.category.slug=martini to your API query.

GET https://api.buttercms.com/v2/pages/cocktails/?&fields.category.slug=martini

{
    "data": [
        {
            "slug": "martini",
            "fields": {
                "name": "Martini",
                "image": "https://cdn.buttercms.com/UKVn6r1RQSVyKoZIVeHU",
                "ingredients": "<p>2 oz. vodka</p>\n<p>1/2 oz. dry vermouth</p>\n<p>Shake ingredients with ice. Strain into a martini glass. Popular garnishes include a lemon twist and olives.</p>",
                "category": {
                    "name": "Martini",
                    "slug": "martini"
                }
             }
        }
    ],
    meta": {
        "count": 1,
        "previous_page": null,
        "next_page": null
    }
}

To take this example further, let's say you wanted multiple Facets to organize your cocktails by. You could set up multiple Collections such as:

  • Drink Types: Cider, Colada, Cosmo, ...
  • Spirits: Bourbon, Whiskey, Gin
  • Color: Brown, Yellow, Orange

Then you would add a corresponding Reference field to link each Collection to your cocktail Pages.

This use case demonstrates is how you can use Collections to add filterable Facets to your Pages.

Reusable Promotional Page Content

There are many use cases for Collections. Another is using Collections to store reusable promotional content that can be Referenced by multiple pages. A common example is customer testimonials. You can store all of your testimonials in a Collection, then Reference those testimonials from your Pages. Here's how you'd do that:

First let's assume your marketing site has some features Pages, each focusing on a particular feature of your product or service.

ButterCMS Feature Page

Here's what the API JSON response looks like for your feature page. You're going to enhance this by adding a Reference to a Testimonials Collection.

GET https://api.buttercms.com/v2/pages/*/full-cms-feature-page

{
    "data": {
        "slug": "full-cms-feature-page",
        "fields": {
            "headline": "Powerful CMS. Zero headache.",
            "hero_image": "https://cdn.buttercms.com/RB2R32WbSxqcanOXiHYA",
            "benefits": [
                {
                    "benefit": "SEO Landing Pages"
                },
                {
                    "benefit": "Customer Case Studies"
                },
                {
                    "benefit": "Company News & Updates"
                }
            ]
        }
    }
}

Create a Collection for testimonials, each having the name of the person, their quote, a headshot, and their title + company.

Testimonials Collection

Then add your customer testimonials to your Collection.

Add Testimonials To Collection

Then add a Reference field from your feature Pages to your Testimonials Collection.

Reference to Testimonials Collection

Now you can easily add multiple testimonials to display on your marketing Pages

Selecting Testimonials From Reference

The API JSON response for your feature page now includes the testimonials you just linked.

GET https://api.buttercms.com/v2/pages/*/full-cms-feature-page

{
    "data": {
        "slug": "full-cms-feature-page",
        "fields": {
            "headline": "Powerful CMS. Zero headache.",
            "hero_image": "https://cdn.buttercms.com/RB2R32WbSxqcanOXiHYA",
            "benefits": [
                {
                    "benefit": "SEO Landing Pages"
                },
                {
                    "benefit": "Customer Case Studies"
                },
                {
                    "benefit": "Company News & Updates"
                }
            ],
            "testimonials": [
                {
                    "name": "Maggie Summers",
                    "headshot": "https://cdn.buttercms.com/iAvdwmxmSjKVfpuqPjWJ",
                    "title_company": "Sasquatch",
                    "quote": "After several attempts at implementing an open source CMS into my app, I found Butter. It’s the best!"
                },
                {
                    "name": "Drew Johnson",
                    "headshot": "https://cdn.buttercms.com/q3z0MfVTJWso2JM5IXvg",
                    "title_company": "App Partner",
                    "quote": "Wordpress was too slow and impacting our business. Butter is more performant and a faster alternative. A no brainer."
                },
                {
                    "name": "BEAU O'HARA",
                    "headshot": "https://cdn.buttercms.com/vOWy5G1LRzm60NyRd3P0",
                    "title_company": "Anstar Products",
                    "quote": "I've tried other API-first CMS'. I liked their programs, but I got yours up and running the fastest"
                }
            ]
        }
    }
}

This use case demonstrates is how you can use Collections to store reusable promotional content that can be Referenced by multiple pages.

Tables of Related Content

There are many use cases for Collections. Another is using Collections as tables of related data which you can query directly. For example let's say you want to create a music site for musicians and you want to store data like Albums and Artists. Here's how you'd model that out using Collections in Butter and then query your content.

For code examples of making API calls to query a Collection directly, check out our Collections API Reference.

First create a Collection for Arists and configure it's properties to be Name, Headshot, and Genre.

Arists Collection

Then add a few Arists to the Collection.

Add Arists To Collection

You can query Collections directly via our API. Here's what the API JSON response looks like for your Artists Collection.

GET https://api.buttercms.com/v2/content/?keys=artists

{
    "data": {
        "artists": [
            {
                "genre": "Rap",
                "name": "Drake",
                "headshot": "https://cdn.buttercms.com/V0mLWb47TaI9qmrRkzAC"
            },
            {
                "genre": "Country",
                "name": "Carrie Underwood",
                "headshot": "https://cdn.buttercms.com/FRToQffDSK2IE1O3fUuq"
            },
            {
                "genre": "Rock",
                "name": "Young the Giant",
                "headshot": "https://cdn.buttercms.com/jqVWtHf6T6acW8APrh3g"
            }
        ]
    }
}

With your Artists Collection created, you can now create a Collection for Albums which will include a Reference to our Artist Collection (every Album belongs to an Artist).

Albums Collection

Then add a few Albums.

Add Ablums To Collection

Here's what the API JSON response looks like for your Albums Collection. Note artist is a Reference the Arists Collection above.

GET https://api.buttercms.com/v2/content/?keys=albums

{
    "data": {
        "albums": [
            {
                "release_date": "2018-06-29T00:00:00",
                "artist": {
                    "genre": "Rap",
                    "name": "Drake",
                    "headshot": "https://cdn.buttercms.com/V0mLWb47TaI9qmrRkzAC"
                },
                "cover_art": "https://cdn.buttercms.com/uorkxsTQfit8N8uW6Im4",
                "album_name": "Scorpion"
            },
            {
                "release_date": "2018-09-14T00:00:00",
                "artist": {
                    "genre": "Country",
                    "name": "Carrie Underwood",
                    "headshot": "https://cdn.buttercms.com/FRToQffDSK2IE1O3fUuq"
                },
                "cover_art": "https://cdn.buttercms.com/3m0oGGyXQNCUnQke4Ps5",
                "album_name": "Cry Pretty"
            },
            {
                "release_date": "2018-10-12T00:00:00",
                "artist": {
                    "genre": "Rock",
                    "name": "Young the Giant",
                    "headshot": "https://cdn.buttercms.com/jqVWtHf6T6acW8APrh3g"
                },
                "cover_art": "https://cdn.buttercms.com/ThLT87lBSzyCkhivr64l",
                "album_name": "Mirror Master"
            }
        ]
    }
}

This use case demonstrates is how you can use Collections to create tables of data that Reference each other for complex content structures.

If you need help after reading this, contact us via email or livechat.

Table of Contents

Introduction

Learn how to quickly build a CMS-powered blog with React. Butter also works with other client-side JavaScript frameworks like Angular and Vue.js. To get started even quicker, here's a set of sample blog templates you can use.

If you need help after reading this, contact us via email or livechat.

Install SDK

If you haven't already, you'll want to install our SDK to make querying your content from our API into your app even easier. Once you've done that, you're ready to begin setting up your blog.

Display posts

To display posts we create a new component in blog.js to fetch and list blog posts from the Butter API. See our API reference for additional options such as filtering by category or author. The response also includes some metadata we'll use for pagination.

In blog.js:

import React from 'react'
import Link from 'next/link'
import Butter from 'buttercms'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps({ query }) {
    let page = query.page || 1;

    const resp = await butter.post.list({page: page, page_size: 10})    
    return resp.data;
  }
  render() {
    const { next_page, previous_page } = this.props.meta;

    return (
      <div>
        {this.props.data.map((post) => {
          return (
            <div><a href={`/post/${post.slug}`}>{post.title}</a></div>
          )
        })}

        <div>
          {previous_page && <Link href={`/?page=${previous_page}`}><a>Prev</a></Link>}
          {next_page && <Link href={`/?page=${next_page}`}><a>Next</a></Link>}
        </div>
      </div>
    )
  }
}

With Next.js getInitialProps will execute on the server on initial page loads, and then on the client when navigating to a different routes using the built-in <Link> component. getInitialProps also receives a context object with various properties – we access the query property for handling pagination. We are fetching posts from a ButterCMS test account – sign in with Github to setup your own posts.

In our render() method we use some clever syntax to only display pagination links only when they're applicable. Our post links will take us to a 404 – we'll get these working next.

Setup the Blog Post page to list a single post

We'll also update our post component to fetch blog posts via slug and render the title and body. See a full list of available post properties in our API reference:

import React from 'react'
import Butter from 'buttercms'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps({ query }) {
    const resp = await butter.post.retrieve(query.slug);  
    return resp.data;
  }
  render() {
    const post = this.props.data;

    return (
      <div>
        <h1>{post.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: post.body }} />
      </div>
    )
  }
}

Add routes to the server

To get our post links working we need to setup dynamic routing for our blog posts. First, create a custom server ./server.js that routes all /posts/:slug URLs to our post component, and the /posts URL to our index page:

const next = require('next')
const express = require('express')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const port = 3000

app.prepare().then(() => {
  const server = express()

  server.get('/posts', (req, res) => {
    return app.render(req, res, '/index', { slug: req.params.slug })
  })

  server.get('/posts/:slug', (req, res) => {
    return app.render(req, res, '/post', { slug: req.params.slug })
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

Finally, update our package.json start script to use our customer server and restart:

"scripts": {
  "start": "node server.js"
}

Previewing Posts

Butter is a headless CMS, which means the design, layout, and general look & feel of your blog is controlled by your own application. As you've seen above, we return your blog content as JSON data, which you then inject into your own templates. In other words, your blog templates are just another set of templates in your app and customizing how your blog looks is the same workflow as any other page in your app. A huge benefit to this is that your blog instantly utilizes all of your existing brand CSS styling so it looks great and visually matches the rest of your app.

Because your app controls the design of your blog, Butter utilizes it to generate live previews for your content editors when they want to preview a blog post before they publish it.

Click here to configure your Blog Preview URL

To setup previewing you will need to tell Butter what your Blog's base preview URL is. i.e.:

https://yoursite.com/blog/

Once that's defined, when you preview a blog post, Butter will append the blog post slug to that preview URL and take you to:

https://yoursite.com/blog/blog-post-slug

To provide a great content editing experience, we highly recommend setting your preview URL.

Categories, Tags, and Authors

Use Butter's APIs for categories, tags, and authors to feature and filter content on your blog.

See our API reference for more information about these objects:

We can use the ButterCMS API to get all post categories and all posts under a category. Let's create routes in the server.js file for the page categories, and the index of pages under a single category:

//...

// Page categories
server.get('/posts/categories', (req, res) => {
  return app.render(req, res, '/categories')
})

// All pages under a single catrogory
server.get('/posts/category/:slug', (req, res) => {
  return app.render(req, res, '/category', { slug: req.params.slug })
})

//...

We can then create the React component for the pages. Create a new file pages/categories.js:

import React from 'react'
import Butter from 'buttercms'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps ({ query }) {
    const resp = await butter.category.list()
    console.log(resp.data)
    return resp.data
  }
  render () {
    return (
      <div>
        {this.props.data.map((category, key) => {
          return (
            <div key={key}>
              <a href={`/posts/category/${category.slug}`}>{category.name}</a>
            </div>
          )
        })}
      </div>
    )
  }
}

This will create a page that will list all categories, along with linking each of them to their own page. Now, create a pages/category.js file, that will contain the component to list all pages under a single category:

import React from 'react'
import Butter from 'buttercms'
import Head from 'next/head'

const butter = Butter('your_api_token')

export default class extends React.Component {
  static async getInitialProps ({ query }) {
    const resp = await butter.category.retrieve(query.slug, {
      include: 'recent_posts'
    })
    return resp.data
  }
  render () {
    const category = this.props.data

    return (
      <div>
        <Head>
          <title>{category.name}</title>
        </Head>
        <h1>{category.name}</h1>
        <div>
          {this.props.data.recent_posts.map((post, key) => {
            return (
              <div key={key}>
                <a href={`/posts/${post.slug}`}>{post.title}</a>
              </div>
            )
          })}
        </div>
      </div>
    )
  }
}

The links on these pages will be to the individual posts themselves.

RSS, Atom, and Sitemap

Butter generates RSS, Atom, and sitemap XML markup. To use these on your blog, return the generated XML from the Butter API with the proper content type headers.

We can fetch the RSS, Atom, and Sitemap feeds using the ButterCMS API, and pipe the response to routes on our server. Create the /sitemap, /rss, and /atom routes inside server.js

server.get('/sitemap', (req, res) => {
  butter.feed.retrieve('sitemap').then((s) => {
    res.send(s.data.data)
  })
})

server.get('/atom', (req, res) => {
  butter.feed.retrieve('atom').then((s) => {
    res.send(s.data.data)
  })
})

server.get('/rss', (req, res) => {
  butter.feed.retrieve('rss').then((s) => {
    res.send(s.data.data)
  })
})

These routes will also update dynamically, everytime new content is added, or updated.

SEO

Next.js provides a <Head> component for setting HTML titles and meta tags. Add import Head from 'next/head' to the top of ./pages/post.js and use the component in the render() method:

render() {
  const post = this.props.data;

  return (
    <div>
      <Head>
        <title>{post.seo_title}</title>
        <meta name="description" content={post.meta_description} />
        <meta name="og:image" content={post.featured_image} />
      </Head>

      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{__html: post.body }} />
    </div>
  )
}

Restart the server and inspect the HTML source of a post to verify that tags are getting set correctly.

Comments

Butter doesn't provide an API for comments due to the excellent existing options that integrate easily. Two popular services we recommend are:

Both products are free, include moderation capabilities, and give your audience a familiar commenting experience. They can also provide some additional distribution for your content since users in their networks can see when people comment on your posts. For a minimalist alternative to Disqus, check out RemarkBox or for an open-source option, Isso.

Social Sharing

To maximize sharing of your content, we recommend using a free tool called AddThis.

They provide an attractive and easy to integrate social sharing widget that you can add to your website.

Social Share Buttons

CSS

Butter integrates into your front-end so you have complete control over the design of your blog. Use the following CSS as boilerplate for post content styling.

.post-container {
  h1, h2, h3, h4, h5 {
    font-weight: 600;
    margin-bottom: 1em;
    margin-top: 1.5em;
  }

  ul, ol {
    margin-bottom: 1.25em;

    li {
      margin-bottom: 0.25em;
    }
  }

  p {
    font-family: Georgia, Cambria, "Times New Roman", Times, serif;
    font-size: 1.25em;
    line-height: 1.58;
    margin-bottom: 1.25em;
    font-weight: 400;
    letter-spacing: -.003em;
  }

  /* Responsive default image width */
  img {
    max-width: 100%;
    height: auto;
  }

  /* Responsive floating */
  @media only screen and (min-width: 720px)  {
    .butter-float-left {
      float: left;
      margin: 0px 10px 10px 0px;
    }

    .butter-float-right {
      float: right;
      margin: 0px 0px 10px 10px;
    }
  }

  /* Image caption */
  figcaption {
    font-style: italic;
    text-align: center;
    color: #ccc;
  }

  p code {
    padding: 2px 4px;
    font-size: 90%;
    color: #c7254e;
    background-color: #f9f2f4;
    border-radius: 4px;
    font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
  }

  pre {
    display: block;
    padding: 1em;
    margin: 0 0 2em;
    font-size: 1em;
    line-height: 1.4;
    word-break: break-all;
    word-wrap: break-word;
    color: #333333;
    background-color: #f5f5f5;
    font-family: Menlo, Monaco,Consolas, "Courier New", monospace;
  }
}

Migration

To import content from another platform like WordPress or Medium, send us an email.

Get started now

Sign up with Google Sign up with Github
or