javascript / expert
Snippet
Server-Side Request Interception with SvelteKit Hooks
SvelteKit hooks allow you to intercept and modify requests before they reach your routes. This is ideal for global middleware tasks like authentication checks and HTML transformations.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
/** @type {import('@sveltejs/kit').Handle} */export async function handle({ event, resolve }) {const token = event.cookies.get('session');if (!token && event.url.pathname.startsWith('/admin')) {return new Response('Unauthorized', { status: 401 });}const response = await resolve(event, {transformPageChunk: ({ html }) => html.replace('%lang%', 'en')});return response;}
svelte
Breakdown
1
export async function handle({ event, resolve })
Defines the central handle hook that processes every request to the server.
2
event.cookies.get('session')
Extracts the session cookie to verify user identity before continuing.
3
transformPageChunk
A callback to modify the HTML buffer dynamically before it is sent to the client.