Creating a Sapper blog using Strapi
Posted on under Engineering
We just published our first few blog posts, and after exploring several different content management systems, we decided to use Strapi. Strapi is an open-source headless CMS written in Node.js; it works with most database management systems and it’s super easy to deploy.
In this quick guide, we’ll go through our process of using the Strapi API with Svelte and Sapper to generate a blog with categories and author pages.
Prerequisites
Before heading to the Svelte code, you should create the following content types in Strapi:
Blog categories
Blog posts
Team members
Each content type contains a title
and slug
, and blog posts and team members also include a rich text field named content
.
Code
We’ll use fs-extra
for writing files, axios
to make requests, markdown-it
to render markdown, and highlight.js
for syntax highlighting. Get started by installing these dependencies:
npm install axios markdown-it highlight-js fs-extra
If you use TypeScript like we do, you’ll need these types installed as well:
npm install --save-dev @types/axios @types/fs-extra @types/highlight.js @types/markdown-it
Then, we create a directory blog
in src/routes
and create a JSON API route [slug].json.js
:
This endpoint will return the contents of blog posts by locating them as JSON files in the data
directory. We will programmatically write these files using a helper. Let’s create a file in the project root, strapi.ts
:
With the above helper, we generate the following files:
src/routes/blog/data/all.json
contains all the blog postssrc/routes/blog/data/SLUG.json
contains each blog post with its slugsrc/routes/blog/authors/data/all.json
contains all the authorssrc/routes/blog/authors/data/SLUG.json
contains each authorsrc/routes/blog/categories/data/all.json
contains all the authorssrc/routes/blog/categories/data/SLUG.json
contains a single author
To generate these, run this script following:
npx ts-node strapi.ts
Then, let’s create some routes. The index.svelte
file in src/routes/blog
will list all blog posts:
Then, we create the single blog post page [slug.svelte]
:
Lastly, we repeat the process and create the index.svelte
and [slug].svelte
routes in the categories and authors directories under blog
, replacing the API URLs.