On this page
Build a SvelteKit App
SvelteKit is a web framework built on top ofSvelte, a modern front-end compiler that builds highlyoptimized vanilla JavaScript. SvelteKit provides features like file-basedrouting, server-side rendering, and full-stack capabilities.
In this tutorial we'll build a simple SvelteKit app with Deno. The app willdisplay a list of dinosaurs. When you click on one, it'll take you to a dinosaurpage with more details. You can see thefinished app on GitHub.
You can see a live version of the app onDeno Deploy.
Want to skip the tutorial and deploy the finished app right now? Click thebutton below to instantly deploy your own copy of the complete SvelteKitdinosaur app to Deno Deploy. You'll get a live, working application that you cancustomize and modify as you learn!
Create a SvelteKit app with DenoJump to heading
We'll useSvelteKit to create a new SvelteKit app. Inyour terminal, run the following command to create a new SvelteKit app:
deno run-A npm:sv create my-app
When prompted, give your app a name and select the "Skeleton project" template.Choose "Yes, using TypeScript syntax" when asked about TypeScript.
Once created,cd
into your new project and run the following command toinstall dependencies:
denoinstall
Then, run the following command to serve your new SvelteKit app:
deno task dev
Deno will run thedev
task from thepackage.json
file which will start theVite development server. Click the output link to localhost to see your app inthe browser.
Configure the formatterJump to heading
deno fmt
supports Svelte files with the--unstable-component
flag. To use it, run this command:
denofmt --unstable-component
To configuredeno fmt
to always format your Svelte files, add this at the toplevel of yourdeno.json
file:
"unstable":["fmt-component"]
Add a backend APIJump to heading
We'll build API routes using SvelteKit's built-in API capabilities. SvelteKitallows you to create API endpoints by creating+server.js
or+server.ts
files in your routes directory.
In thesrc/routes
directory, create anapi
folder. In that folder, create adata.json
, which will contain the hard coded dinosaur data.
Copy and pastethis json fileinto thesrc/routes/api/data.json
file. (If you were building a real app, youwould probably fetch this data from a database or an external API.)
We're going to build out some API routes that return dinosaur information.SvelteKit provides a simple way to create API endpoints using server files.
Createsrc/routes/api/dinosaurs/+server.ts
to handle the/api/dinosaurs
endpoint. This will return all dinosaurs:
import{ json}from"@sveltejs/kit";import datafrom"../data.json"with{type:"json"};exportfunctionGET(){returnjson(data);}
Then createsrc/routes/api/dinosaurs/[id]/+server.ts
to handle individualdinosaur requests at/api/dinosaurs/:id
:
import{ json}from"@sveltejs/kit";importtype{ RequestHandler}from"./$types";import datafrom"../../data.json"with{ type:"json"};exportconstGET:RequestHandler=({ params})=>{const dinosaur= data.find((item)=>{return item.name.toLowerCase()=== params.id.toLowerCase();});if(dinosaur){returnjson(dinosaur);}returnjson({ error:"Not found"},{ status:404});};
SvelteKit automatically handles routing based on the file structure. The+server.ts
files define API endpoints, and the[id]
folder creates a dynamicroute parameter.
Build the frontendJump to heading
File-based routing and data loadingJump to heading
SvelteKit uses file-based routing, where the structure of yoursrc/routes
directory determines your app's routes. Unlike Vue Router, you don't need toconfigure routes manually - SvelteKit automatically creates routes based on yourfile structure.
In SvelteKit,+page.svelte
files define page components, and+page.ts
filesdefine data loading functions that run before the page loads. This providesbuilt-in server-side rendering and data fetching capabilities.
The pages and componentsJump to heading
SvelteKit organizes the frontend into pages and components. Pages are defined by+page.svelte
files in the routes directory, while components can be reusablepieces of code stored anywhere in your project.
Each Svelte component file contains three optional sections:<script>
,<template>
(the HTML), and<style>
. The<script>
tag contains theJavaScript/TypeScript logic, the template contains the HTML markup, and the<style>
tag contains scoped CSS.
We'll create pages for the home page and individual dinosaur details, along withdata loading functions to fetch dinosaur information from our API.
The home pageJump to heading
The home page will display a list of dinosaurs fetched from our API. First,createsrc/routes/+page.ts
to load the dinosaur data:
importtype{ PageLoad}from"./$types";exportconst load:PageLoad=async({ fetch})=>{const res=awaitfetch(`/api/dinosaurs`);const dinosaurs=await res.json();return{ dinosaurs};};
This load function runs on both the server and client, and the data is passed tothe page component. Thefetch
function is provided by SvelteKit and works inboth server and client environments.
Next, updatesrc/routes/+page.svelte
to display the dinosaur list:
<scriptlang="ts">import type{ PageProps}from"./$types";let{ data}: PageProps=$props();let dinosaurs= data.dinosaurs;</script><main><h1>🦕 Dinosaur app</h1><p>Click on a dinosaur below to learn more.</p> {#each dinosaurs as dinosaur (dinosaur.name)}<ahref="/{dinosaur.name.toLowerCase()}"class="dinosaur"> {dinosaur.name}</a> {/each}</main>
This code uses Svelte'seach blockto iterate over thedinosaurs
array and render each dinosaur as a link. The{#each}
block is Svelte's way of rendering lists, and the(dinosaur.name)
provides a unique key for each item.
The Dinosaur detail pageJump to heading
The dinosaur detail page will display information about a specific dinosaur.SvelteKit uses folder names in square brackets to create dynamic routes. The[dinosaur]
folder creates a route that captures the dinosaur name from theURL.
First, createsrc/routes/[dinosaur]/+page.ts
to load individual dinosaur data:
importtype{ PageLoad}from"./$types";import{ error}from"@sveltejs/kit";exportconst load:PageLoad=async({ fetch, params})=>{const res=awaitfetch(`/api/dinosaurs/${params.dinosaur}`);const dinosaur=await res.json()as{ name:string; description:string};if(res.status===404){returnerror(404,"No dinosaur found");}return{ dinosaur};};
This load function uses theparams
object to access thedinosaur
parameterfrom the URL. If the API returns a 404, we use SvelteKit'serror
function tothrow a 404 error.
Next, createsrc/routes/[dinosaur]/+page.svelte
to display the dinosaurdetails:
<scriptlang="ts">import type{ PageProps}from"./$types";let{ data}: PageProps=$props();let dinosaur= data.dinosaur;</script><div><h1>{dinosaur.name}</h1><p>{dinosaur.description}</p><ahref="/">🠠 Back to all dinosaurs</a></div>
This page displays the dinosaur's name and description, along with a link backto the home page. The data comes from the load function and is automaticallyavailable in the component.
Run the appJump to heading
Now that we've set up the frontend and backend API routes, we can run the app.In your terminal, run the following command:
deno task dev
This will start the SvelteKit development server with Vite. SvelteKitautomatically handles both the frontend pages and the API routes we created, soyou don't need to run separate servers.
Visithttp://localhost:5173
in your browser to see the app. Click on adinosaur to see more details!
You can see a live version of the app onDeno Deploy.
Build and deployJump to heading
SvelteKit comes with built-in build capabilities. We configured it to use theDeno adapter, which optimizes the build for deployment on Deno-compatibleplatforms. Run the following command to build the app in production mode:
deno task build
This will:
- Build the SvelteKit app using Vite
- Generate optimized production assets
- Create server-side code compatible with Deno
The built app will be ready for deployment on platforms that support Deno, suchas Deno Deploy.
You can deploy this app to your favorite cloud provider. We recommend usingDeno Deploy for a simple and easy deploymentexperience. You can deploy your app directly from GitHub, simply create a GitHubrepository and push your code there, then connect it to Deno Deploy.
Create a GitHub repositoryJump to heading
Create a new GitHub repository, then initialize andpush your app to GitHub:
git init-b maingit remoteadd origin https://github.com/<your_github_username>/<your_repo_name>.gitgitadd.git commit-am'my svelte app'git push-u origin main
Deploy to Deno DeployJump to heading
Once your app is on GitHub, you candeploy it to Deno Deploy.
For a walkthrough of deploying your app, check out theDeno Deploy tutorial.
🦕 Now that you can run a SvelteKit app in Deno with the Deno adapter you'reready to build real world applications!