GitHub can serve as the editing interface, version control system and content store for a static site generator, while GitHub Actions tests and deploys each change to Cloudflare Workers. The resulting stack is deliberately thin: a Markdown editor, a generator such as Metalsmith, GitHub with Actions for CI/CD, and Cloudflare Workers Sites, which carries a cost of about $5 per month.

Prerequisites and project layout

Two accounts are required: GitHub (with GitHub Actions) and Cloudflare Workers Sites. A Markdown editor such as Typora is recommended but optional. The completed project lives on GitHub.

The finished directory structure looks like this:

├── build.js
├── .github/workflows
│   ├── deploy.yml
│   └── nodejs.js
├── layouts
│   ├── about.hbs
│   ├── article.hbs
│   ├── index.hbs
│   └── partials
│       └── navigation.hbs
├── package-lock.json
├── package.json
├── public
├── src
│   ├── about.md
│   ├── articles
│   │   ├── post1.md
│   │   └── post2.md
│   └── index.md
├── workers-site
└── wrangler.toml

Scaffolding and build script

Start from an empty project. The first command creates a directory, moves into it and initializes npm:

$ mkdir cms && cd cms && npm init -y

Then install the dependencies — the core one being the Metalsmith static site generator, alongside a handful of supporting packages:

$ npm install --save-dev metalsmith metalsmith-markdown metalsmith-layouts metalsmith-collections metalsmith-permalinks handlebars jstransformer-handlebars

The directory tree and starter files are created in a few terminal steps: make the directories, create the build file, add the layouts, then set up the content resources.

$ mkdir -p src/articles &&  mkdir -p layouts/partials 
$ touch build.js
$ touch layouts/index.hbs && touch layouts/about.hbs && touch layouts/article.hbs && touch layouts/partials/navigation.hbt
$ touch src/index.md && touch src/about.md && touch src/articles/post1.md && touch src/articles/post1.md touch src/articles/post2.md

The project folder should then look something like this:

├── build.js
├── layouts
│   ├── about.hbs
│   ├── article.hbs
│   ├── index.hbs
│   └── partials
│       └── navigation.hbs
├── package-lock.json
├── package.json
└── src
    ├── about.md
    ├── articles
    │   ├── post1.md
    │   └── post2.md
    └── index.md

Why Metalsmith

Any of the major generators — Eleventy, Gatsby, Hugo, Jekyll, Hexo, Vuepress — could drive this setup. Metalsmith is chosen for its simplicity and extensibility; a working site can be produced by the code in the source material. Its plugin ecosystem (plugin list) covers stylesheets, tags and more beyond this walkthrough.

Content and templates

Articles require front matter to render. The files to edit are index.md, post1.md and post2.md, and the metadata block should look like this:

---
title: 'Post1'
layout: article.hbs 
---
## Post content here....

Mock content pulled from GitHub Gists can be substituted for hand-written posts:

$ curl https://gist.githubusercontent.com/jppope/35dd682f962e311241d2f502e3d8fa25/raw/ec9991fb2d5d2c2095ea9d9161f33290e7d9bb9e/index.md > src/index.md
$ curl https://gist.githubusercontent.com/jppope/2f6b3a602a3654b334c4d8df047db846/raw/88d90cec62be6ad0b3ee113ad0e1179dfbbb132b/about.md > src/about.md
$ curl https://gist.githubusercontent.com/jppope/98a31761a9e086604897e115548829c4/raw/6fc1a538e62c237f5de01a926865568926f545e1/post1.md > src/articles/post1.md
$ curl https://gist.githubusercontent.com/jppope/b686802621853a94a8a7695eb2bc4c84/raw/9dc07085d56953a718aeca40a3f71319d14410e7/post2.md > src/articles/post2.md

Templating uses Handlebars.js, though Metalsmith is largely agnostic about template languages. The index layout iterates the articles collection with {{#each }} and reserves a slot for a partial, {{>navigation }}, which is defined later. The About page and the Articles page share the same layout; the duplication is intentional, to show how additional pages are added. The navigation partial itself is filled in as follows:

<div class="navigation">
  <div>
    <a class="button" href="/">Home</a>
    <a class="button" href="https://css-tricks.com/about">About</a>
  </div>
</div>

Anatomy of the build file

Metalsmith predates widespread ES module adoption and relies on CommonJS, so the build file uses require statements rather than imports — this avoids an extra Babel step and matches most existing tutorials. Dependencies are imported first:

// What we use to glue everything together
const Metalsmith = require('metalsmith');


// compile from markdown (you can use targets as well)
const markdown = require('metalsmith-markdown');


// compiles layouts
const layouts = require('metalsmith-layouts');


// used to build collections of articles
const collections = require('metalsmith-collections');


// permalinks to clean up routes
const permalinks = require('metalsmith-permalinks');


// templating
const handlebars = require('handlebars');


// register the navigation
const fs = require('fs');
handlebars.registerPartial('navigation', fs.readFileSync(__dirname + '/layouts/partials/navigation.hbt').toString());


// NOTE: Uncomment if you want a server for development
// const serve = require('metalsmith-serve');
// const watch = require('metalsmith-watch');

Metalsmith is then configured with its source and target directories:

// Metalsmith
Metalsmith(__dirname)            
  // where your markdown files are
  .source('src')      
  // where you want the compliled files to be rendered
  .destination('public')

Markdown rendering, layout rendering and the "articles" collection are declared next. Collections group files — blog posts here, but equally recipes or anything else — and the markdown and layouts plugins do the conversion work; inside a template, {{{contents}}} inserts the rendered body.

 // previous code would go here


  // collections create groups of similar content
  .use(collections({ 
    articles: {
      pattern: 'articles/*.md',
    },
  }))
  // compile from markdown
  .use(markdown())
  // nicer looking links
  .use(permalinks({
    pattern: ':collection/:title'
  }))
  // build layouts using handlebars templates
  // also tell metalsmith where to find the raw input
  .use(layouts({
    engine: 'handlebars',
    directory: './layouts',
    default: 'article.html',
    pattern: ["*/*/*html", "*/*html", "*html"],
    partials: {
      navigation: 'partials/navigation',
    }
  }))


// NOTE: Uncomment if you want a server for development
// .use(serve({
//   port: 8081,
//   verbose: true
// }))
// .use(watch({
//   paths: {
//     "${source}/**/*": true,
//     "layouts/**/*": "**/*",
//   }
// }))

The build method closes the script:

// Everything else would be above this
.build(function(err) {
  if (err) {
    console.error(err)
  }
  else {
    console.log('build completed!');
  }
});

Assembled, the complete file reads:

const Metalsmith = require('metalsmith');
const markdown = require('metalsmith-markdown');
const layouts = require('metalsmith-layouts');
const collections = require('metalsmith-collections');
const permalinks = require('metalsmith-permalinks');
const handlebars = require('handlebars');
const fs = require('fs');


// Navigation
handlebars.registerPartial('navigation', fs.readFileSync(__dirname + '/layouts/partials/navigation.hbt').toString());


Metalsmith(__dirname)
  .source('src')
  .destination('public')
  .use(collections({
    articles: {
      pattern: 'articles/*.md',
    },
  }))
  .use(markdown())
  .use(permalinks({
    pattern: ':collection/:title'
  }))
  .use(layouts({
    engine: 'handlebars',
    directory: './layouts',
    default: 'article.html',
    pattern: ["*/*/*html", "*/*html", "*html"],
    partials: {
      navigation: 'partials/navigation',
    }
  }))
  .build(function (err) {
    if (err) {
      console.error(err)
    }
    else {
      console.log('build completed!');
    }
  });

One update to package.json wires up the build script; the commented sections of the build file can serve the project locally via npm run build but must be removed before deployment.

 "name": "buffaloTraceRoute",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "node build.js",
    "test": "echo \"No Tests Yet!\" "
  },
  "keywords": [],
  "author": "Your Name",
  "license": "ISC",
  "devDependencies": {
    // these should be the current versions
    // also... comments aren't allowed in JSON
  }
}

Cloudflare Workers Sites: deployment target

GitHub Pages and Netlify are viable alternatives, but Cloudflare has three advantages in this context. Deployed sites are served from 190+ data centers, cutting latency by serving assets from a location physically near the user.

Courtesy of Cloudflare

Configuration can be fiddly for anyone unfamiliar with environment variables, but once local credentials are in place, publishing from the site directory is a single wrangler publish; the CI/CD route covered here adds some setup but stays simple.

ServiceFree Tier BandwidthPaid Tier PricePaid Tier Requests / Bandwidth
GitHub Pages100GBN/AN/A
Netlify100GB$45~150K / 400 GB
Cloudflare Workers Sitesnone$510MM / unlimited 
Calculations assume a 3MB average website. Cloudflare has additional limits on CPU use. GitHub Pages should not be used for sites that have credit card transactions.

On cost: GitHub Pages and Netlify impose a soft 100GB monthly bandwidth limit. GitHub Pages offers nothing beyond it, and Netlify's next tier is $45/month, against Cloudflare's $5/month for 10 million requests. There is no free tier at Cloudflare, and GitHub Pages has suffered outages over the past year — acceptable for a demo, not for a business. Cloudflare also bundles free SSL, DNS routing, a custom Workers Sites domain useful for staging, unlimited environments, and domain registration at cost.

Wrangler configuration

Install the Cloudflare CLI, Wrangler, then add Cloudflare Sites to the project:

$ npm i @cloudflare/wrangler -g
wrangler init --site cms 

The expected terminal output at this point:

⬇️ Installing cargo-generate...
🔧   Creating project called `workers-site`...
✨   Done! New project created /Users/<User>/Code/cms/workers-site
✨  Succesfully scaffolded workers site
✨  Succesfully created a `wrangler.toml`

This generates a /workers-site folder and a wrangler.toml config in the project root. Update its bucket property, then grab the Account ID and Zone ID from the bottom of the Cloudflare dashboard for your domain. Do not skip the "Get your API token" button — that token is needed for the GitHub Actions secret in the next section, so store it somewhere handy.

bucket = "./public"

Add the IDs to the .toml file (the values in the source are fake):

name = "buffalo-traceroute"
type = "webpack"
account_id = "d7313702f333457f84f3c648e9d652ff" # Fake... use your account_id
workers_dev = true
# route = "example.com/*" 
# zone_id = "805b078ca1294617aead2a1d2a1830b9" # Fake... use your zone_id


[site]
bucket = "./public"
entry-point = "workers-site"
(Again, those IDs are fake.)

If credentials are requested on your machine, run wrangler config.

CI/CD with GitHub Actions

First activate GitHub Actions on the account (it was technically in beta at the time of writing, apparently without incident). Create a GitHub repository and push the project. Guidance on Git/GitHub mechanics is out of scope — this introduction covers it — and the push commands, run from the project root, are:

# run commands one after the other
$ git init
$ touch .gitignore && echo 'node_modules' > .gitignore
$ git add .
$ git commit -m 'first commit'
$ git remote add origin https://github.com/{username}/{repo name}
$ git push -u origin master

In the repository, create a .github/workflows directory at the project root. GitHub can also create it automatically by enabling the "node" workflow; at the time of writing, adding an Actions workflow is part of GitHub's UI. Two workflow files follow, one per role: validating pull requests ("CI") and deploying merges to master ("CD").

# integration.yml
name: Integration


on:
  pull_request:
    branches: [ master ]


jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [10.x, 12.x]
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm ci
    - run: npm run build --if-present
    - run: npm test
      env:
        CI: true
  1. on: triggers only when a pull request targets the master branch.
  2. jobs: runs on two Node environments (Node 10 and Node 12; 12 is the recommended version), building where a build script exists and running tests where a test script exists.

The deployment workflow is more involved:

# deploy.yml
name: Deploy


on:
  push:
    branches:
      - master


jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    strategy:
      matrix:
        node-version: [10.x]


    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm install
      - uses: actions/checkout@master
      - name: Build site
        run: "npm run build"
      - name: Publish
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}

Store the Cloudflare API token as a repository secret: go to project settings, add a secret named CF_API_TOKEN and paste the token. In the workflow, on: fires when code is merged into master, and steps: installs dependencies with Node, builds the site, then publishes it via the Cloudflare Wrangler. The project state before a build (excluding node_modules) is:

├── build.js
├── dist
│   └── worker.js
├── layouts
│   ├── about.hbs
│   ├── article.hbs
│   ├── index.hbs
│   └── partials
│       └── navigation.hbs
├── package-lock.json
├── package.json
├── public
├── src
│   ├── about.md
│   ├── articles
│   │   ├── post1.md
│   │   └── post2.md
│   └── index.md
├── workers-site
│   ├── index.js
│   ├── package-lock.json
│   ├── package.json
│   └── worker
│       └── script.js
└── wrangler.toml

GitHub as the CMS

This is the part that delivers the promised CMS: the editing workflow needs no custom interface.

  1. Write a Markdown file with front matter.
  2. Open the project repository on GitHub.
  3. Enter the "Articles" directory and upload the file. When GitHub asks whether to create a new branch with a pull request, answer yes.
  4. Once the integration check passes, merge the pull request, which triggers deployment.
  5. About ten seconds later the content is live on 164 data centers worldwide.

Troubleshooting

  • Layouts occasionally misbehave. Add DEBUG=metalsmith-layouts npm run build before the build step to get useful output.
  • At times Actions required committing node_modules to deploy — odd and not a recommended practice, but it resolved the problem.
  • For assets such as images and SVGs, metalsmith-assets-improved is a good option.
CSS-Tricks star logo