Page 3: Data Loading and API Endpoints

3. Data Loading and API Endpoints

SvelteKit provides a powerful data loading mechanism using load functions, which can fetch data on both the server and client.

3.1. Fetching Data with load Functions (+page.js / +page.server.js)

A load function in a +page.js file can run on both the server and client, while a load function in a +page.server.js file runs exclusively on the server.

// src/routes/posts/[slug]/+page.server.js
export async function load({ params }) {
  const res = await fetch(\`https://api.example.com/posts/\${params.slug}\`);
  const post = await res.json();
  return { post };
}

In +page.svelte, you can access the loaded data directly as a prop:

// src/routes/posts/[slug]/+page.svelte
<script>
  export let data; // The \`data\` prop contains the value returned from the load function.
</script>
<h1>{data.post.title}</h1>
<p>{data.post.content}</p>

3.2. API Endpoints (+server.js)

You can create backend API endpoints using +server.js files. Export functions for each HTTP method (GET, POST, PUT, DELETE).

// src/routes/api/items/+server.js
import { json } from '@sveltejs/kit';

export async function GET() {
  const items = [{ id: 1, name: 'Item A' }, { id: 2, name: 'Item B' }];
  return json(items);
}

export async function POST({ request }) {
  const newItem = await request.json();
  // Logic to save to database...
  return json({ message: 'Item added!', item: newItem }, { status: 201 });
}