← Back to all posts

Building a Markdown Blog with SvelteKit

By Mark •
sveltekitmarkdownblogtutorial

Building a Markdown Blog with SvelteKit

Creating a markdown blog is an excellent way to learn SvelteKit's core concepts. Let's build one!

Why Markdown?

Markdown is perfect for blogs because:

  • Simple syntax - Easy to write and read
  • Portable - Plain text files that work everywhere
  • Version control friendly - Git diffs work great
  • Fast - No database needed for simple blogs

Project Structure

Here's how we'll organize our blog:

src/
ā”œā”€ā”€ posts/
│   ā”œā”€ā”€ post-one.md
│   ā”œā”€ā”€ post-two.md
│   └── post-three.md
└── routes/
    └── blog/
        ā”œā”€ā”€ +page.svelte       # List all posts
        ā”œā”€ā”€ +page.ts           # Load all posts
        └── [slug]/
            ā”œā”€ā”€ +page.svelte   # Display single post
            └── +page.ts       # Load single post

Required Dependencies

We need two packages:

npm install marked gray-matter
  • marked - Converts markdown to HTML
  • gray-matter - Parses YAML frontmatter

Frontmatter

Each markdown file starts with YAML metadata:

---
title: My Blog Post
date: 2024-03-05
author: Mark
description: A great blog post
---

This metadata is perfect for:

  • Displaying post previews
  • Sorting posts by date
  • Adding SEO meta tags

Loading Posts

In SvelteKit, we use load functions to fetch data:

// +page.ts
export async function load() {
  const posts = await getAllPosts();
  return { posts };
}

The returned data is available in your component via data prop!

Rendering Markdown

Use marked to convert markdown to HTML:

import { marked } from 'marked';

const html = marked(markdown);

Then render it in Svelte:

{@html html}

Conclusion

Building a markdown blog teaches you:

  • File-based routing
  • Load functions
  • Dynamic routes
  • Static site generation

It's the perfect first SvelteKit project! šŸŽ‰