Chuyển đến nội dung

Bài 33 · Projects

Project: A Markdown Blog with SvelteKit

Build a fast, SEO-friendly blog in SvelteKit - Markdown posts with front matter, import.meta.glob, dynamic routes, entries(), prerendering, an RSS feed and a 404 page.

This project brings the SvelteKit chapter together. You will build a blog whose posts are plain Markdown files in your repository: no database, no admin panel, fast static pages, good SEO and an RSS feed. It uses routing, load, prerendering, an endpoint, error pages and <svelte:head>.

SvelteKit and Vite cannot run on this site, so the project files are read-only. The <TryIt> blocks run the core logic (front matter parsing, a small Markdown converter, slug routing, the RSS feed) in plain JavaScript so you can test each idea.

The plan

flowchart LR
  M["src/posts/*.md"] --> L["$lib/posts.js (parse + sort)"]
  L --> I["/ list page"]
  L --> P["/blog/[slug] post page"]
  L --> R["/rss.xml endpoint"]
  P --> S["prerender at build time"]

Markdown files are parsed once; three routes share the result.

Create the project with npx sv create blog, choose the minimal template, and install two small libraries: npm install marked. (Another popular choice is mdsvex, which lets you use Svelte components inside Markdown; we use a plain converter to keep each step visible.)

TEXT
src/
  posts/
    hello-svelte.md
    runes-explained.md
  lib/
    posts.js
  routes/
    +layout.svelte
    +layout.js              prerender = true
    +page.svelte            post list
    +page.js
    blog/[slug]/+page.svelte
    blog/[slug]/+page.js
    rss.xml/+server.js
    +error.svelte

Step 1: posts with front matter

Each file starts with front matter between --- lines, then Markdown:

MARKDOWN
---
title: Hello, Svelte
date: 2026-03-01
summary: Why this blog exists.
tags: [intro, svelte]
---

Welcome! This blog is built with **SvelteKit** and a folder of Markdown files.

## What you will find

- Short lessons
- Real code

Step 2: load all posts

Vite's import.meta.glob imports many files at once at build time. With query: '?raw' you get each file's text:

JavaScript
// src/lib/posts.js
import { marked } from 'marked';

const files = import.meta.glob('/src/posts/*.md', { query: '?raw', import: 'default', eager: true });

function parseFrontMatter(raw) {
  const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(raw.replace(/\r\n/g, '\n'));
  if (!match) return { data: {}, body: raw };
  const data = {};
  for (const line of match[1].split('\n')) {
    const i = line.indexOf(':');
    if (i === -1) continue;
    const key = line.slice(0, i).trim();
    let value = line.slice(i + 1).trim();
    if (value.startsWith('[') && value.endsWith(']')) {
      value = value.slice(1, -1).split(',').map((s) => s.trim()).filter(Boolean);
    }
    data[key] = value;
  }
  return { data, body: match[2] };
}

export const posts = Object.entries(files)
  .map(([path, raw]) => {
    const { data, body } = parseFrontMatter(raw);
    return {
      slug: path.split('/').pop().replace(/\.md$/, ''),
      title: data.title ?? 'Untitled',
      date: data.date,
      summary: data.summary ?? '',
      tags: data.tags ?? [],
      html: marked.parse(body),
    };
  })
  .sort((a, b) => (a.date < b.date ? 1 : -1));   // newest first (ISO dates sort as text)

export const getPost = (slug) => posts.find((p) => p.slug === slug);

Because the files are read at build time, nothing touches the file system at request time.

JS Front matter, sorting and slugs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 3: the list page

JavaScript
// src/routes/+page.js
import { posts } from '$lib/posts.js';

export function load() {
  return { posts: posts.map(({ html, ...meta }) => meta) };   // do not ship every post's HTML to the list page
}
HTML
<!-- src/routes/+page.svelte -->
<script>
  let { data } = $props();
</script>

<svelte:head>
  <title>My Svelte Blog</title>
  <meta name="description" content="Short lessons about Svelte and SvelteKit." />
</svelte:head>

<h1>Posts</h1>
<ul>
  {#each data.posts as post (post.slug)}
    <li>
      <a href="/blog/{post.slug}">{post.title}</a>
      <time datetime={post.date}>{new Date(post.date).toLocaleDateString('en-US', { dateStyle: 'long' })}</time>
      <p>{post.summary}</p>
    </li>
  {/each}
</ul>

Step 4: the post page

JavaScript
// src/routes/blog/[slug]/+page.js
import { error } from '@sveltejs/kit';
import { getPost, posts } from '$lib/posts.js';

export function load({ params }) {
  const post = getPost(params.slug);
  if (!post) error(404, 'Post not found');
  return { post };
}

export function entries() {
  return posts.map((p) => ({ slug: p.slug }));   // tell the prerenderer every slug
}
HTML
<!-- src/routes/blog/[slug]/+page.svelte -->
<script>
  let { data } = $props();
  const post = $derived(data.post);
</script>

<svelte:head>
  <title>{post.title}</title>
  <meta name="description" content={post.summary} />
  <meta property="og:title" content={post.title} />
</svelte:head>

<article>
  <h1>{post.title}</h1>
  <time datetime={post.date}>{post.date}</time>
  {@html post.html}
</article>

{@html} is safe here because you wrote the Markdown. Never use it for text submitted by visitors; sanitize it first or render as text.

Make the whole site static by adding one line:

JavaScript
// src/routes/+layout.js
export const prerender = true;

With adapter-static the build writes real HTML files for /, every /blog/<slug> and rss.xml, so any CDN can serve the blog (see Rendering Modes and Deployment).

Step 5: a tiny Markdown converter, and why you want a library

marked handles the full language. To see what such a library does, this converter handles headings, bold, italic, inline code, links and lists, escaping HTML first:

JS A mini Markdown to HTML converter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line shows why escaping matters: the <script> tag is turned into text. Real libraries add many more features (code fences, tables, nested lists, reference links) and edge cases; use one in production.

Step 6: RSS feed and 404 page

JavaScript
// src/routes/rss.xml/+server.js
import { posts } from '$lib/posts.js';

export const prerender = true;

const site = 'https://example.com';
const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

export function GET() {
  const items = posts.map((p) => `
    <item>
      <title>${esc(p.title)}</title>
      <link>${site}/blog/${p.slug}</link>
      <guid>${site}/blog/${p.slug}</guid>
      <pubDate>${new Date(p.date).toUTCString()}</pubDate>
      <description>${esc(p.summary)}</description>
    </item>`).join('');

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><channel>
  <title>My Svelte Blog</title><link>${site}</link><description>Short lessons about Svelte.</description>${items}
</channel></rss>`;

  return new Response(xml, { headers: { 'Content-Type': 'application/xml' } });
}
HTML
<!-- src/routes/+error.svelte -->
<script>
  import { page } from '$app/state';
</script>

<h1>{page.status === 404 ? 'Page not found' : 'Something went wrong'}</h1>
<p><a href="/">Back to all posts</a></p>
JS Generating the RSS feed

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 7: ship it

  1. npm install -D @sveltejs/adapter-static and set it in svelte.config.js.
  2. npm run build writes the site to build/; test it with npm run preview.
  3. Upload build/ to any static host (Netlify, Cloudflare Pages, GitHub Pages, an S3 bucket).
  4. Add a sitemap.xml endpoint in the same style as the RSS feed and a robots.txt in static/.

Ideas to extend it

  • Tag pages at /tags/[tag] with entries() listing all tags.
  • Pagination through ?page= read from url.searchParams (then the list route cannot be prerendered unless you generate page routes instead).
  • Reading time computed from word count.
  • Syntax highlighting for code blocks at build time (a marked extension or Shiki).
  • Switch to mdsvex to embed live Svelte components inside posts.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does import.meta.glob('/src/posts/*.md', { query: '?raw', eager: true }) do?

    Vite resolves the glob at build time; eager imports include the files in the bundle, and ?raw returns their text.
  2. 2. What is the export function entries() for in a dynamic route?

    The prerenderer follows links, but entries() guarantees pages that are not linked anywhere are still built.
  3. 3. Why is {@html post.html} acceptable here but not for visitor comments?

    {@html} inserts raw HTML. Only use it with trusted or sanitized content.
  4. 4. Which line makes every route of the blog prerendered?

    Page options in a layout apply to all routes below it; prerender = true renders them at build time.

Summary

  • Markdown files plus import.meta.glob give you a database-free content layer; parse front matter once in $lib/posts.js.
  • A list route, a [slug] route with entries() and a +server.js RSS endpoint cover the whole blog.
  • prerender = true with adapter-static produces plain HTML for any CDN.
  • Set <title> and meta tags with <svelte:head>; use {@html} only for trusted content.

Next: Practice Exercises

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.