SvelteKit allows you to create more than just pages. We can also create API routes by adding a +server.js
file that exports functions corresponding to HTTP methods: GET
, PUT
, POST
, PATCH
and DELETE
.
This app fetches data from a /roll
API route when you click the button. Create that route by adding a src/routes/roll/+server.js
file:
src/routes/roll/+server
export function GET() {
const number = Math.floor(Math.random() * 6) + 1;
return new Response(number, {
headers: {
'Content-Type': 'application/json'
}
});
}
Clicking the button now works.
Request handlers must return a Response object. Since it’s common to return JSON from an API route, SvelteKit provides a convenience function for generating these responses:
src/routes/roll/+server
import { json } from '@sveltejs/kit';
export function GET() {
const number = Math.floor(Math.random() * 6) + 1;
return new Response(number, {
headers: {
'Content-Type': 'application/json'
}
});
return json(number);
}
previous next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
/** @type {number} */
let number = $state();
async function roll() {
const response = await fetch('/roll');
number = await response.json();
}
</script>
<button onclick={roll}>Roll the dice</button>
{#if number !== undefined}
<p>You rolled a {number}</p>
{/if}