Files
template-sanity/template/ROUTING_GUIDE.md

2.6 KiB

SvelteKit Routing Guide

This guide explains how the dynamic routing system works in this Sanity + SvelteKit template, including URL patterns and content management.

URL Structure

The template uses the following URL patterns:

Custom Pages

  • Pattern: /{slug}
  • Example: /about, /contact, /services
  • Content Type: custom pages from Sanity
  • Route File: src/routes/[slug]/+page.svelte

Blog Posts

  • Pattern: /blog/{slug}
  • Example: /blog/my-first-post, /blog/web-development-tips
  • Content Type: blog posts from Sanity
  • Route File: src/routes/blog/[slug]/+page.svelte

Blog Index

  • Pattern: /blog
  • Shows: List of all blog posts
  • Route File: src/routes/blog/+page.svelte

File Structure

src/routes/
├── [slug]/                          # Custom pages at root level
│   ├── +page.server.ts             # Server-side data loading
│   └── +page.svelte                # Custom page component
├── blog/
│   ├── +page.server.ts             # Blog index server load
│   ├── +page.svelte                # Blog index component
│   └── [slug]/                     # Individual blog posts
│       ├── +page.server.ts         # Blog post server load
│       └── +page.svelte            # Blog post component
├── +layout.server.ts               # Global layout data
└── +layout.svelte                  # Global layout component

How It Works

1. URL Resolution Order

SvelteKit resolves URLs in this order:

  1. Exact routes (e.g., /blog)
  2. Parameterized routes (e.g., /blog/[slug], /[slug])

This means:

  • /blog → Blog index page
  • /blog/some-post → Blog post page
  • /about → Custom page (if exists)
  • /nonexistent → 404 error

2. Data Loading Flow

Custom Pages (/[slug])

// +page.server.ts
const CUSTOM_QUERY = `*[_type == "custom" && slug.current == $slug][0]`;
const custom = await serverClient.fetch(CUSTOM_QUERY, { slug });

Blog Posts (/blog/[slug])

// +page.server.ts
const BLOG_QUERY = `*[_type == "blog" && slug.current == $slug][0]`;
const blog = await serverClient.fetch(BLOG_QUERY, { slug });

3. Content Types

Custom Page Schema

type Custom = {
  _id: string;
  _type: 'custom';
  title?: string;
  slug?: Slug;
  tags?: Array<string>;
  publishedAt?: string;
  body?: BlockContent;
  seoTitle?: string;
  seoDescription?: string;
}

Blog Post Schema

type Blog = {
  _id: string;
  _type: 'blog';
  title?: string;
  slug