0
0
SvelteHow-ToBeginner · 3 min read

How to Create Routes in SvelteKit: Simple Guide

In SvelteKit, you create a route by adding a file or folder inside the src/routes directory. Each file corresponds to a URL path, so a file named about.svelte creates the /about route automatically.
📐

Syntax

Routes in SvelteKit are created using the file system inside the src/routes folder. Each .svelte file or folder represents a route path.

  • src/routes/index.svelte/ (home page)
  • src/routes/about.svelte/about
  • src/routes/blog/post.svelte/blog/post
  • src/routes/[id].svelte → dynamic route like /123
plaintext
src/routes/
  index.svelte    // maps to '/' route
  about.svelte    // maps to '/about' route
  blog/
    post.svelte   // maps to '/blog/post' route
  [id].svelte     // maps to dynamic route '/:id' where id is a variable
💻

Example

This example shows how to create a simple /about route by adding an about.svelte file inside src/routes. When you visit /about in the browser, it renders the content of this file.

svelte
<script>
  // No script needed for static content
</script>

<h1>About Us</h1>
<p>Welcome to the about page of our SvelteKit app.</p>
Output
<h1>About Us</h1><p>Welcome to the about page of our SvelteKit app.</p>
⚠️

Common Pitfalls

1. Forgetting to place files inside src/routes: Routes only work if files are inside this folder.

2. Using wrong file extensions: Only .svelte files create routes.

3. Not using square brackets for dynamic routes: To create a route with a variable part, use [param].svelte.

plaintext
/* Wrong: file outside routes folder */
// src/about.svelte  <-- This will NOT create a route

/* Right: file inside routes folder */
// src/routes/about.svelte  <-- This creates '/about' route

/* Wrong: dynamic route without brackets */
// src/routes/id.svelte  <-- This creates '/id' route literally

/* Right: dynamic route with brackets */
// src/routes/[id].svelte  <-- This creates '/:id' dynamic route
📊

Quick Reference

Route TypeFile/Folder NameURL Path Example
Home pageindex.svelte/
Static routeabout.svelte/about
Nested routeblog/post.svelte/blog/post
Dynamic route[id].svelte/123 or /abc
Nested dynamicblog/[slug].svelte/blog/my-post

Key Takeaways

Create routes by adding .svelte files inside src/routes folder.
Use index.svelte for the home page route (/).
Use square brackets [param].svelte for dynamic routes.
Nested folders create nested URL paths automatically.
Only files inside src/routes with .svelte extension become routes.