0
0
Svelteframework~5 mins

File-based routing in Svelte

Choose your learning style9 modes available
Introduction

File-based routing lets you create web pages by making files. Each file becomes a page automatically.

When building a website with many pages and you want simple navigation.
When you want to add or remove pages quickly without writing extra code.
When you want your folder structure to match your website's URL paths.
When you want to avoid manually setting up routes in your app.
When you want to keep your project organized and easy to understand.
Syntax
Svelte
src/routes/
  +page.svelte
  about/+page.svelte
  blog/[slug]/+page.svelte

Each +page.svelte file inside src/routes folder becomes a route.

Folders inside src/routes create URL paths. Square brackets [ ] define dynamic parts.

Examples
This file creates the home page at URL /.
Svelte
src/routes/+page.svelte
This file creates the about page at URL /about.
Svelte
src/routes/about/+page.svelte
This file creates dynamic blog pages like /blog/post1 or /blog/post2. The [slug] part changes based on the URL.
Svelte
src/routes/blog/[slug]/+page.svelte
Sample Program

This example shows three pages: home, about, and a dynamic blog post page. The blog page changes content based on the URL part after /blog/.

Svelte
// File: src/routes/+page.svelte
<script>
  let message = "Welcome to the home page!";
</script>

<h1>{message}</h1>

// File: src/routes/about/+page.svelte
<script>
  let info = "This is the about page.";
</script>

<h1>About</h1>
<p>{info}</p>

// File: src/routes/blog/[slug]/+page.svelte
<script>
  import { page } from '$app/stores';
</script>

<h1>Blog Post: {$page.params.slug}</h1>
<p>This page shows the blog post with slug: {$page.params.slug}</p>
OutputSuccess
Important Notes

Dynamic routes use [param] syntax to capture URL parts.

File names must be +page.svelte for pages to work.

Nested folders create nested URLs automatically.

Summary

File-based routing creates pages from files and folders.

Use +page.svelte files inside src/routes to make pages.

Dynamic routes use square brackets to capture URL parts.