0
0
Svelteframework~5 mins

Why SvelteKit handles full-stack routing

Choose your learning style9 modes available
Introduction

SvelteKit manages routing for both the frontend and backend in one place. This makes building web apps simpler and faster.

When you want to build a website that needs both pages and server actions.
When you want to avoid setting up separate servers for frontend and backend.
When you want your app to load pages quickly with server-side rendering.
When you want to handle API requests and page navigation in the same project.
When you want to keep your code organized by combining routes and server logic.
Syntax
Svelte
src/routes/
  +page.svelte       // Frontend page component
  +page.server.js    // Server-side code for that page
  +server.js         // API endpoints for backend logic

SvelteKit uses special files like +page.svelte for frontend pages and +server.js for backend routes.

This folder structure lets SvelteKit know what code runs on the client and what runs on the server.

Examples
This is a simple frontend page that users see when they visit /about.
Svelte
src/routes/about/+page.svelte
// This file shows the About page content to users.
This server file sends data to the About page before it loads.
Svelte
src/routes/about/+page.server.js
export function load() {
  return { info: 'About info from server' };
}
This backend route handles API requests at /api/data and sends JSON data.
Svelte
src/routes/api/data/+server.js
export function GET() {
  return new Response(JSON.stringify({ message: 'Hello from API' }), { status: 200 });
}
Sample Program

This example shows a main page that gets data from the server before showing it. It also has an API route that returns JSON data.

Svelte
// File: src/routes/+page.svelte
<script>
  export let data;
</script>
<h1>Welcome to SvelteKit</h1>
<p>Message from server: {data.message}</p>

// File: src/routes/+page.server.js
export function load() {
  return { message: 'Hello from server-side load!' };
}

// File: src/routes/api/hello/+server.js
export function GET() {
  return new Response(JSON.stringify({ greeting: 'Hello from API!' }), { status: 200 });
}
OutputSuccess
Important Notes

SvelteKit routing combines frontend and backend in one place, reducing setup time.

Server routes run only on the server, so they can safely handle secrets and databases.

Using full-stack routing helps keep your app organized and easier to maintain.

Summary

SvelteKit handles both frontend pages and backend routes using a simple folder structure.

This approach makes building full-stack apps easier and faster.

You can fetch data on the server and send it to pages before they load.