Considering SvelteKit hooks for data fetching
The user is asking about implementing dynamic server-side data fetching in a SvelteKit project using hooks, which include handle, handleFetch, and handleError in src/hooks.server.ts. They might want to centralize fetch configuration or intercept requests. This could mean fetching data before the page loads using something like "handle" with "resolve" and "event.fetch." I'll analyze use-cases and provide example code for SvelteKit 1.0+, showcasing how to inject data into locals and utilize it in load for dynamic fetching.Exploring dynamic server-side fetching in SvelteKit
The user is asking about implementing dynamic server-side data fetching in SvelteKit using hooks. They might be interested in unifying the API base URL depending on the environment or specifics of each request. I need to introduce SvelteKit's data fetching, explain hooks like handle and handleFetch, and show how to implement dynamic fetching by customizing handleFetch for things like external API calls and setting auth headers. I'll include an example with an external REST API and discuss intercepting requests dynamically, possibly mentioning streaming as well.Creating a SvelteKit example
I'm designing an example for SvelteKit's dynamic server-side fetching. In src/hooks.server.ts, I'll create a handle function that checks for an auth token in cookies, fetching user data from an external API. If the user is authenticated, I can set that data in event.locals. I'll also implement handleFetch to intercept requests to the external API and ensure the auth token is included.
Then, in +page.server.ts, I'll structure the load function to fetch a post and its comments asynchronously, using the provided parameters.Implementing dynamic SSR fetching with hooks
In my example, I have the load function that checks if the API request for a post and its comments was successful. If not, I throw a 404 error. Additionally, the user specifically asked about dynamic server-side data fetching using hooks.
One approach could be to fetch global settings in the handle hook, storing them in event.locals.config. This way, we get dynamic configuration for each request. Then, in +layout.server.ts, I can easily return this configuration for reuse. This method allows for flexibility across nested pages.Planning a guide for SvelteKit data fetching
The user is asking for a clear guide on implementing dynamic server-side data fetching in SvelteKit using hooks, specifically focused on hooks.server.ts. I need to lay out prerequisites, like setting up a SvelteKit project, and explain the use of the handle hook for per-request logic with event.fetch and event.locals.
I should also cover the handleFetch for intercepting fetch calls, provide example code, mention TypeScript definitions, and explain dynamic data reading from URL parameters and cookies. It should be concise yet comprehensive. Below is a concrete pattern for dynamic server‑side data fetching in SvelteKit using hooks (src/hooks.server.ts) plus how to consume that data in +layout.server.ts / +page.server.ts.
1. What hooks give you
SvelteKit’s server hooks run on every request and let you:
- Fetch data on the server before pages load
- Attach that data to
event.locals
- Configure how
fetch behaves on the server (e.g. add auth headers, base URL, logging, etc.)
The key hooks:
handle: central per-request logic
handleFetch: intercept and modify all server-side fetch calls
2. Define your types (src/app.d.ts)
So locals can be typed:
// src/app.d.ts
// This file is auto-picked by SvelteKit
declare global {
namespace App {
interface Locals {
user: { id: string; name: string } | null;
settings: { theme: string; language: string } | null;
}
}
}
export {};
3. Implement hooks.server.ts with dynamic fetching
3.1 Use handle to fetch per-request data
Here we:
- Read a token from cookies
- Fetch the current user
- Fetch global settings
- Store both on
event.locals for later use in load functions
// src/hooks.server.ts
import type { Handle, HandleFetch } from '@sveltejs/kit';
const API_BASE = 'https://api.example.com';
export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get('token');
// 1. Fetch user only if we have a token
let user = null;
if (token) {
const res = await event.fetch(`${API_BASE}/me`, {
headers: {
Authorization: `Bearer ${token}`
}
});
if (res.ok) {
user = await res.json();
} else if (res.status === 401) {
// Token is invalid -> delete it if you wish
event.cookies.delete('token', { path: '/' });
}
}
// 2. Fetch some global per-request settings
const settingsRes = await event.fetch(`${API_BASE}/settings`);
const settings = settingsRes.ok ? await settingsRes.json() : null;
// 3. Attach to locals so all server load functions can access them
event.locals.user = user;
event.locals.settings = settings;
// 4. Let SvelteKit render the route as usual
return resolve(event);
};
Now any +layout.server.ts or +page.server.ts can read locals.user and locals.settings.
3.2 Use handleFetch to centralize server-side fetch behavior
handleFetch runs whenever server code calls fetch. You can:
- Automatically prepend a base URL
- Inject auth headers
- Add logging / metrics
- Modify requests differently per route or user
// src/hooks.server.ts (continued)
export const handleFetch: HandleFetch = async ({ event, request, fetch }) => {
const url = new URL(request.url);
// Example 1: Redirect internal "/api/*" calls to an external API
if (url.pathname.startsWith('/api/')) {
const token = event.cookies.get('token');
// Build external URL dynamically
const target = new URL(url.pathname.replace('/api', ''), API_BASE);
// Clone the original request but change the URL
request = new Request(target, {
method: request.method,
headers: request.headers,
body: request.body,
// include any other options you need
});
// Add auth header dynamically
if (token) {
const headers = new Headers(request.headers);
headers.set('Authorization', `Bearer ${token}`);
request = new Request(request, { headers });
}
}
// Example 2: Log all outgoing server fetches if you want
// console.log('Server fetch:', request.method, request.url);
return fetch(request);
};
Now, in your server load functions, you can just call fetch('/api/...'); handleFetch will transform that into requests to your real backend with headers attached.
4. Use the data in +layout.server.ts / +page.server.ts
4.1 Global layout: expose user and settings to all pages
// src/routes/+layout.server.ts
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ locals }) => {
// locals.* were set in hooks.server.ts
return {
user: locals.user,
settings: locals.settings
};
};
In +layout.svelte:
<!-- src/routes/+layout.svelte -->
<script lang="ts">
export let data: {
user: { id: string; name: string } | null;
settings: { theme: string; language: string } | null;
};
</script>
{#if data.user}
<p>Welcome, {data.user.name}!</p>
{/if}
<slot />
4.2 Dynamic route: fetch page-specific data (still SSR)
Use both params and fetch (which goes through handleFetch) to get dynamic data:
// src/routes/posts/[id]/+page.server.ts
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ params, fetch, locals }) => {
const { id } = params;
// These fetch calls will be processed through handleFetch
const [postRes, commentsRes] = await Promise.all([
fetch(`/api/posts/${id}`),
fetch(`/api/posts/${id}/comments`)
]);
if (!postRes.ok) {
throw error(postRes.status, 'Post not found');
}
return {
user: locals.user, // from hooks
post: await postRes.json(), // per-request, server-side fetched
comments: await commentsRes.json()
};
};
And in the page component:
<!-- src/routes/posts/[id]/+page.svelte -->
<script lang="ts">
export let data;
</script>
<h1>{data.post.title}</h1>
<p>By {data.user?.name ?? 'Guest'}</p>
<h2>Comments</h2>
{#each data.comments as comment}
<p>{comment.body}</p>
{/each}
5. When to use which piece
-
Use +page.server.ts / +layout.server.ts:
- For route-specific or layout-specific data
- When you want SSR and access to cookies/locals
-
Use handle in hooks.server.ts:
- For per-request concerns that apply to many routes:
- Authentication
- User lookup
- Global configuration
- Locale detection
-
Use handleFetch in hooks.server.ts:
- To centralize how server-side
fetch works:
- Base URLs
- Auth headers
- Logging
- Proxying internal paths to external APIs
Together, this pattern gives you dynamic, centralized server-side data fetching in a SvelteKit app using hooks. If you describe your backend shape (REST, GraphQL, etc.), I can tailor the hook and load examples specifically to that.