Using Airtable as a Headless CMS with Bridgetown

onurozer

Onur Ozer

Posted on June 9, 2022

Using Airtable as a Headless CMS with Bridgetown

Bridgetown is a wonderful static site generator. It uses markdown files by default, but I recently found out that it can also use an external API to generate resources.

Here's how to integrate it with Airtable:

Setting up

First, get your keys ready:

Create a .env file in your Bridgetown project root with these keys:

AIRTABLE_API_KEY = "yourAPIkey"
AIRTABLE_BASE_ID = "yourBaseID"
AIRTABLE_TABLE_NAME = "yourTableName"
Enter fullscreen mode Exit fullscreen mode

Don't forget to set these environment variables in your production environment as well.

Finally, add these to your Gemfile and run bundle install.

gem "airrecord"
gem "dotenv"
Enter fullscreen mode Exit fullscreen mode

Build script

Create a ruby file in your plugins/builders folder and customise it to map your Airtable fields to your frontmatter

# plugins/builders/airtable.rb
require 'dotenv/load'
require 'airrecord'

class Builders::Airtable < SiteBuilder
  def build

    # setup keys
    api_key = ENV['AIRTABLE_API_KEY']
    base_id = ENV['AIRTABLE_BASE_ID']
    table_name = ENV['AIRTABLE_TABLE_NAME']

    # query records using airrecord
    records = Airrecord.table(api_key, base_id, table_name).all

    # map airtable fields to frontmatter
    records.each do |record|
      add_resource :posts, "#{Bridgetown::Utils.slugify(record['Title'])}.md" do
        layout :post
        title record['Title']
        description record['Description']
        tags record['Tags']
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

That's it. Your resources will now be generated from Airtable.

Bonus: Deploy to Netlify from Airtable

How do you trigger a new build when the records on Airtable change? Netlify build hooks and Airtable Apps to the rescue.

  1. Create a build hook on Netlify
  2. Add a custom app on your Airtable base
  3. Write a simple script in your app to make a post request:
let netlifyURL = 'https://api.netlify.com/build_hooks/yourBuildHookID'
let response = await fetch(netlifyURL, {method: 'POST'});
Enter fullscreen mode Exit fullscreen mode

This will add a Run button right inside Airtable that triggers a build every time you run it. Have fun!

💖 💪 🙅 🚩
onurozer
Onur Ozer

Posted on June 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related