Skip to content

Instantly share code, notes, and snippets.

@KoljaL
Created October 10, 2022 12:35
Show Gist options
  • Save KoljaL/c570e0ab856fbb2ade0f7203ab5b50cf to your computer and use it in GitHub Desktop.
Save KoljaL/c570e0ab856fbb2ade0f7203ab5b50cf to your computer and use it in GitHub Desktop.
Routuing in SvelteKit - try to mak a CheatSheet

Routuing in SvelteKit

a CheatSheet

Basics

Folder based routing

  • All routes are inside the folder src/routes/.
  • Every route is a folder: src/routes/about for https://myblog.org/about/.
  • The folders name is the name of the route in the browser.
  • There are no index.* files for routes, instead:
  • Every rechable route (-folder) must contains a +page.svelte file to represent the content.
  • A dynamic route uses braces [] for their variables
    • routes/atricle-[slug]/ for myblog.org/article-1 or myblog.org/article-last.
    • Inside the routes/atricle-[slug]/+page.svelte you can get the slug via the load() function.
  • Inside the routes/ folder you can hide folders and files with an underscore _, to hide them for the SvelteKit-Router.

Layout

  • Every route can have their own layout, contains in the +layout.svelte file.
  • Every subroute inherits the layout of its parent-route, instead it has its own +layout.svelte file.

load() function

  • Before rendering the page (+page.svelte) SvelteKit will look for files inside a route-folder named like +page.js or +page.server.js to run the load() function inside of them.
  • If you use TypeScript the files are named corresponding: +page.ts or +page.server.ts.
  • The load() function will return the data object as prop to the +page.svelte file.
  • To execute a load() function for all subroutes inside a route, create a +layout.js with the load() function inside.

+page.js and +page.server.js

  • +page.js will be executed on the server and inside the client (browser).
  • page.server.js will only be executed on the server, so it can respond to HTTP requests like GET or POST.

Example

Folder structure

routes
│   +layout.svelte   
│   +page.svelte
│
└───about
│      +page.svelte
└───article-[slug]
       +page.js
       +page.svelte

routes/+layout.svelte

<nav>
  <a href="/">Home</a>
  <a href="/about">About</a> 
</nav>

<slot></slot>

routes/+page.svelte

<h1>Home</h1>

routes/about/+page.svelte

<h1>About</h1>

routes/article[slug]/+page.js

import { error } from '@sveltejs/kit';
 
/** @type {import('./$types').PageLoad} */
export function load({ params }) {
  if (params.slug === 'hello-world') {
    return {
      title: 'Hello world!',
      content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
    };
  }
 
  throw error(404, 'Not found');
}

routes/article[slug]/+page.svelte

<script>
/** @type {import('./$types').PageData} */  
  export let data;
</script>

<h1>{data.title}</h1>
<div>{@html data.content}</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment