Skip to main content
Bases de Svelte
Introduction
Réactivité
Props
Logique
Évènements
Liaisons
Classes et styles
Actions
Transitions
Svelte avancé
Réactivité avancée
Réutiliser du contenu
Mouvements
Liaisons avancées
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

SvelteKit provides several hooks — ways to intercept and override the framework’s default behaviour.

The most elementary hook is handle, which lives in src/hooks.server.js. It receives an event object along with a resolve function, and returns a Response.

resolve is where the magic happens: SvelteKit matches the incoming request URL to a route of your app, imports the relevant code (+page.server.js and +page.svelte files and so on), loads the data needed by the route, and generates the response.

The default handle hook looks like this:

src/hooks.server
export async function handle({ event, resolve }) {
	return await resolve(event);
}

For pages (as opposed to API routes), you can modify the generated HTML with transformPageChunk:

src/hooks.server
export async function handle({ event, resolve }) {
	return await resolve(event, {
		transformPageChunk: ({ html }) => html.replace(
			'<body',
			'<body style="color: hotpink"'
		)
	});
}

You can also create entirely new routes:

src/hooks.server
export async function handle({ event, resolve }) {
	if (event.url.pathname === '/ping') {
		return new Response('pong');
	}

	return await resolve(event, {
		transformPageChunk: ({ html }) => html.replace(
			'<body',
			'<body style="color: hotpink"'
		)
	});
}

Modifier cette page sur Github

1
2
<h1>hello world</h1>
<a href="/ping">ping</a>