Explaining secure server fetch interception in SvelteKit
The handleFetch hook runs only on the server and can intercept all server-side fetch requests, making it perfect to inject secrets like API keys or mTLS credentials without exposing them to clients. The example will show parsing request URLs to target internal microservices only, adding Authorization headers from private environment variables, and how to attach an undici Agent for mTLS in Node 18+. It will clarify the distinction between undici’s dispatcher option versus https.Agent for client certs, ensuring proper secure handling inside src/hooks.server.ts.
In SvelteKit you get one place to intercept every server‑side fetch call: handleFetch in src/hooks.server.(ts|js). Because it only runs on the server, it’s a safe place to add secrets like an internal API key or client cert without risking sending them to the browser.
A minimal example that:
- Reads a service‑to‑service key from a private env var.
- Detects calls to your internal hosts.
- Clones the
Request to add an Authorization header before passing it to the real fetch.
// src/hooks.server.ts
import type { HandleFetch } from '@sveltejs/kit';
import { INTERNAL_API_KEY, INTERNAL_HOSTS } from '$env/static/private';
// You can also hardcode INTERNAL_HOSTS, e.g. ['api.internal.local', 'usersvc:8080']
const internalHosts = INTERNAL_HOSTS?.split(',').map((h) => h.trim()) ?? [];
export const handleFetch: HandleFetch = async ({ request, fetch, event }) => {
// Only mutate requests that go to your internal services
const url = new URL(request.url);
if (internalHosts.includes(url.host)) {
const headers = new Headers(request.headers);
headers.set('Authorization', `Bearer ${INTERNAL_API_KEY}`);
// Optional: propagate user/session info to downstream services
if (event.locals.userId) {
headers.set('X-User-Id', event.locals.userId);
}
const authedRequest = new Request(request, { headers });
return fetch(authedRequest);
}
// Everything else goes through unchanged
return fetch(request);
};
Usage anywhere on the server:
// +page.server.ts or +server.ts
export const load = async ({ fetch }) => {
// This will be intercepted by handleFetch and get the Authorization header automatically
const res = await fetch('http://usersvc.internal.local/api/users/me');
return { user: await res.json() };
};
Adding mTLS (adapter‑node / Node 18+)
If your internal calls require mutual TLS, you can supply a client certificate by giving fetch a custom dispatcher (Undici) or agent (https). With the default Node 18+ runtime and adapter‑node, SvelteKit’s fetch is Undici under the hood, so use dispatcher:
// src/hooks.server.ts
import { Agent as UndiciAgent } from 'undici';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { CERT_PATH, KEY_PATH, CA_PATH } from '$env/static/private';
const mtlsDispatcher = new UndiciAgent({
connect: {
cert: readFileSync(join(process.cwd(), CERT_PATH)),
key: readFileSync(join(process.cwd(), KEY_PATH)),
ca: CA_PATH ? readFileSync(join(process.cwd(), CA_PATH)) : undefined
}
});
export const handleFetch: HandleFetch = async ({ request, fetch }) => {
const url = new URL(request.url);
if (internalHosts.includes(url.host)) {
const headers = new Headers(request.headers);
headers.set('Authorization', `Bearer ${INTERNAL_API_KEY}`);
const authedRequest = new Request(request, { headers });
// Pass dispatcher with mTLS credentials
return fetch(authedRequest, { dispatcher: mtlsDispatcher });
}
return fetch(request);
};
If you’re on an older Node/fetch that supports agent (https.Agent), you can instead pass { agent: new https.Agent({ cert, key, ca, rejectUnauthorized: true }) }.
A few notes:
- Import secrets with
$env/static/private so they are not bundled into client code.
handleFetch in hooks.server.ts only runs for server‑side fetches (+server routes, load on the server, endpoints, actions). Client‑side fetches are not touched.
- Always scope injection to known internal hosts/paths to avoid leaking credentials to arbitrary URLs.