Use the fetch passed to a universal load. SvelteKit automatically tracks /api/todos as a dependency.
Check the status and content type before reading JSON. Error responses aren't always JSON.
import { error } from '@sveltejs/kit';
export async function load({ fetch }) {
const response = await fetch('/api/todos');
if (!response.ok) error(502, 'Could not load todos');
const type = response.headers.get('content-type') ?? '';
if (!type.includes('application/json')) {
error(502, 'Expected JSON from the todo API');
}
return { todos: await response.json() };
}
export const prerender = false;