How to create a blog with Svelte and dev.to API

Gianmarco Cavallo
2 min readOct 31, 2021
Photo by Lukas Blazek on Unsplash

I developed my personal website using svelteKit and I decided to add a Blog section where I would have shown all my articles, today I’m gonna show you how you can do the same using Sveltekit + DEV.TO public API.

Disclaimer: I’m not going to cover the CSS part but only the “functional” one.

Routing

SvelteKit uses a filesystem-based router. This means that the structure of your application is defined by the structure of the files in the src/routes folder ( like nextjs does).

In order to define our blog structure, we need to create a blog folder and within it we need to create to files:

  1. index.svelte is just going to be rendered when you visit yourDomain.com/blog and we are going to show the list of our dev.to articles here.
  2. [slug].svelte is going to be rendered when you visit yourDomain.com/blog/yourDevToPostId and we are going to show the single article when you click on it.

So far so good, now let’s give a look in detail at each of them.

Index.svelte

The main file (index.svelte) it's structured in the following way, let’s give it a look.

Anything exported from a context="module" script block becomes an export from the module itself.

The value articles is being called in the next script block and then used in the code below where we can loop the array of articles and get the data of the single article, such as the title, tags and the id.

[slug].svelte

The structure of [slug].svelte is very simple, as we did in index.svelte in a similar way, we are going to fetch the single article with page.params.slug to get the content of the single article, slug comes from the name of the file, e.g. [test].svelte -> page.params.test .

@html is a special function that allows us to parse the html article content (article.body_html).

Now you just need to style your pages/components and you are ready to deploy your blog section on your website too!.

--

--