Morgan Conrad

New Website Infrastructure-2


Background

Previously, I described using metalsmith and Netlify to build this website. But there was still an issue that I couldn't "blog from my tablet while sipping margaritas on a sailboat".

Enter Contentful

Contentful is an online content management system that offers a very reasonable free tier. You create a hierarchical content model with "types", such as a "post", containing various fields such as a title, slug, date, tags, and contents. Such fields have types such as "Short text", "Date & time", "Long text". With some planning you can set these to match up to the relevant fields (YAML data) for Metalsmith to process. You can also upload "media" such as images, audio, PDFs. (I haven't done much with media.)

Normally (?) you would edit the content in your browser, at least that's what I do, but Contentful provides four APIs to interact with the data, including editing. The only API I have used, to retrieve the finished blog post, is the Content Delivery API which provides read-only access to retrieve JSON representations of the data. Perfect. They provide an NPM module, contentful to do the basics.

Linking to metalsmith

There's an existing module, contentful-metalsmith, to retrieve your content, but I didn't like that it required you to setup a "fake" .html file to trigger the retrieval. But definitely check it out, it's reasonably popular and might suit your needs and thinking.

I preferred an approach where the files just get added with programatic control. From that point on, they will be treated just like files read from disk. This was important because I already have several blog entries on disk and didn't want to be required to upload them to Contentful. They can transparently share the same layout files. Plus, I like writing metalsmith plugins. :-)

The result is metalsmith-get-contentful. You provide your API client credentials, an optional query to select, for example, the content_type, and directions (in msFiles) on how to identify and store the data as a "file". For example:

{
  client: {
    accessToken : 64character string...,
    space : your space ID (12 characters?)
  },
  query: {
    content_type: 'post'
  }
  msFiles: {
    idField: 'slug',
    filename: "posts/${id}.md"
  }
}

Results

From anywhere with internet access, perhaps a tablet on my sailboat, I can login to Contentful, and create a new blog post (or edit an existing one). Then publish the post, trigger a Netlify rebuild, then return to my margarita. Wonderful!