Sveltekit Changes: Routes

Sveltekit Changes: Routes

Introduction

As you know, In last article I explained Load Function changes where I also mentioned about new routes changes and now we gonna look how they works and what they are now.

If you see a tree I'll will be showing it from src/routes directory.

New Directory Based Routing

Now, In sveltekit everything looks new it's also goes for routing. We all have been fan of file-based routing but sveltekit comes with new routing which is directory based.
So now you define a folder than add your +page.svelte, +page.js, +page.server.js files as per need where:

  1. +page.svelte is for your client side code with all the html, css and js for client.

  2. +page.js is for Load function which i have explained in detail.

  3. +page.server.js is for all server side code earlier you may know it by the name shadow endpoint. Here you define all the form actions for the route.

That's the overview we need to get some more details. So we start from layout and gonna end at server routes.

  • Layouts

Now theres is nothing like __layout.svelte and it's replaced with +layout.svelte and now you have to more things to look on those are +layout.js and layout.server.js.

// +layout.svelte

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

<slot></slot>
Enter fullscreen mode Exit fullscreen mode

+layout.svelte going to work same as __layout.svelte but you need to define Load Function inside +layout.js. And if you need Load Function to run on server you going to use layout.server.js.

export function load() {
  return {
    sections: [
      { slug: 'profile', title: 'Profile' },
      { slug: 'notifications', title: 'Notifications' }
    ]
  };
}
Enter fullscreen mode Exit fullscreen mode

But here comes the twist you can only do Load Functions in layout.server.js no http request handling here which comes in +page.server.js, so never get confused in this.

+layout.js, +layout.server.js can export page options — prerender, ssr and csr.

  • Error Page

If an error occurs during load, SvelteKit will render a default error page. You can customise this error page on a per-route basis by adding an +error.svelte file (So there is no __error.svelte now):

<script>
  import { page } from '$app/stores';
</script>

<h1>{$page.status}: {$page.error.message}</h
Enter fullscreen mode Exit fullscreen mode
  • +page

A +page.svelte component defines a page of your app. So your / route will be +page.svelte inside src/routes/. Which will be your client side code.

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

<h1>{data.title}</h1>
<div>{@html data.content}</div>
Enter fullscreen mode Exit fullscreen mode

A +page.js files handles load function of that route. For more detailed explanation read Sveltekit Changes: Load Function.

A page.server.js file handles your server side code in which you handle your form actions.

// page.server.js or `+page.js`
import { error } from '@sveltejs/kit';

/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
  const post = await getPostFromDatabase(params.slug);

  if (post) {
    return post;
  }

  throw error(404, 'Not found');
}
Enter fullscreen mode Exit fullscreen mode

If load lets you read data from the server, actions let you write data to the server using the

element

So if you want a route named about you have create a directory inside src/routes directory with the name about. Inside that you will add +page.svelte and if you need load function add +page.js and also wanna use form actions and server side rendering ad +page.server.js.

I know it's alot to degist first but after one project you are sold for the idea.

  • +sever Routes

Sometimes we need API or endpoints for our http requests then you can simply use +server.js. So if you wanna create a API or Endpoint by the name login, You will create a directory inside src/routes by the name login and add +server.js file inside it.

These endpoints are capable of HTTP request methods eg. GET, POST, PATCH, PUT AND DELETE and it works on request and response method of http requests.

// `+server.js`

import { error } from '@sveltejs/kit';

/** @type {import('./$types').RequestHandler} */
export function GET({ url }) {
  const min = Number(url.searchParams.get('min') ?? '0');
  const max = Number(url.searchParams.get('max') ?? '1');

  const d = max - min;

  if (isNaN(d) || d < 0) {
    throw error(400, 'min and max must be numbers, and min must be less than max');
  }

  const random = min + Math.random() * d;

  return new Response(String(random));
}
Enter fullscreen mode Exit fullscreen mode

new Response is a reponse object that will return a response to client.

  • Finally the Routes Tress
.
├── (authed)
│   ├── +layout.server.ts
│   ├── +layout.svelte
│   └── dashboard
│       ├── +page.svelte
│       └── +page.ts
├── (unauthed)
│   ├── +layout.server.ts
│   ├── +layout.svelte
│   ├── +page.svelte
│   ├── +page.ts
│   ├── createAdmin
│   │   ├── +page.server.ts
│   │   └── +page.svelte
│   └── login
│       ├── +page.server.ts
│       └── +page.svelte
└── api
Enter fullscreen mode Exit fullscreen mode

Here you can see a file structure of my project and you might have seen some weird folder with name inside parentheses. Those are grouped layouts. We will discuss them later.

I'll suggest you to migrate your old projects to newer one to understand it more better.

This is me writing for you. If you wanna ask or suggest anything please put it in comment.

© 2023 EtherCorps. All rights reserved.