Tutorials API call
In SvelteKit, we can create API endpoints by creating a
+server.ts
file in any subdirectory in the
src/routes
folder. By convention, typically the
src/routes/api
subdirectory is used for this purpose.Making fetch requests
To get data from an external API or an API endpoint in your project, you can use the
provided
fetch
function. Thanks to SvelteKit, this will automatically make a credentialed request to your
server, as it inherits cookies for the page request./src/routes/profile/+page.svelte
1 const loadUser = async () => {
2 const res = await fetch('/api/user');
3
4 return await res.json();
5 }
Protected API routes
Thanks to Svelte server hooks and Lucia, we can automatically protect our endpoints by
checking for a valid user session via cookies. Check the user authentication tutorial if you haven't setup Lucia yet.
/src/routes/api/user/+server.ts
1import type { RequestEvent } from '@sveltejs/kit';
2
3export async function GET(event: RequestEvent): Promise<Response> {
4 if (event.locals.user) {
5 return new Response(JSON.stringify(event.locals.user), {
6 status: 200,
7 headers: {
8 'Content-Type': 'application/json'
9 }
10 });
11 }
12
13 return new Response(null, {
14 status: 401
15 });
16}