Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和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"'
		)
	});
}

Edit this page on GitHub

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