Skip to content

feat: Add handleLoad hooks on client and server #9543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fifty-snakes-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

add `handleLoad` and `handleServerLoad` hook support
4 changes: 4 additions & 0 deletions packages/kit/src/core/sync/write_client_manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ export function write_client_manifest(kit, manifest_data, output, metadata) {
handleError: ${
hooks_file ? 'client_hooks.handleError || ' : ''
}(({ error }) => { console.error(error) }),

handleLoad: ${
hooks_file ? 'client_hooks.handleLoad || ' : ''
}(({ event, resolve }) => { return resolve(event) }),
};

export { default as root } from '../root.svelte';
Expand Down
7 changes: 5 additions & 2 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,9 @@ export function create_client(app, target) {
if (DEV) {
try {
lock_fetch();
data = (await node.universal.load.call(null, load_input)) ?? null;
data =
(await app.hooks.handleLoad({ event: load_input, resolve: node.universal.load })) ??
null;
if (data != null && Object.getPrototypeOf(data) !== Object.prototype) {
throw new Error(
`a load function related to route '${route.id}' returned ${
Expand All @@ -702,7 +704,8 @@ export function create_client(app, target) {
unlock_fetch();
}
} else {
data = (await node.universal.load.call(null, load_input)) ?? null;
data =
(await app.hooks.handleLoad({ event: load_input, resolve: node.universal.load })) ?? null;
}
data = data ? await unwrap_promises(data) : null;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/src/runtime/server/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ declare module '__SERVER__/internal.js' {
handle?: import('types').Handle;
handleError?: import('types').HandleServerError;
handleFetch?: import('types').HandleFetch;
handleLoad?: import('types').HandleLoad;
handleServerLoad?: import('types').HandleServerLoad;
}>;
}
3 changes: 2 additions & 1 deletion packages/kit/src/runtime/server/data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ export async function render_data(
}
}
return data;
}
},
handleServerLoad: options.hooks.handleServerLoad
});
} catch (e) {
aborted = true;
Expand Down
4 changes: 3 additions & 1 deletion packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ export class Server {
handle: module.handle || (({ event, resolve }) => resolve(event)),
// @ts-expect-error
handleError: module.handleError || (({ error }) => console.error(error?.stack)),
handleFetch: module.handleFetch || (({ request, fetch }) => fetch(request))
handleFetch: module.handleFetch || (({ request, fetch }) => fetch(request)),
handleLoad: module.handleLoad || (({ event, resolve }) => resolve(event)),
handleServerLoad: module.handleServerLoad || (({ event, resolve }) => resolve(event))
};
}
}
Expand Down
6 changes: 4 additions & 2 deletions packages/kit/src/runtime/server/page/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ export async function render_page(event, page, options, manifest, state, resolve
if (parent) Object.assign(data, await parent.data);
}
return data;
}
},
handleServerLoad: options.hooks.handleServerLoad
});
} catch (e) {
load_error = /** @type {Error} */ (e);
Expand Down Expand Up @@ -180,7 +181,8 @@ export async function render_page(event, page, options, manifest, state, resolve
resolve_opts,
server_data_promise: server_promises[i],
state,
csr
csr,
handleLoad: options.hooks.handleLoad
});
} catch (e) {
load_error = /** @type {Error} */ (e);
Expand Down
23 changes: 16 additions & 7 deletions packages/kit/src/runtime/server/page/load_data.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import { validate_depends } from '../../shared.js';
* state: import('types').SSRState;
* node: import('types').SSRNode | undefined;
* parent: () => Promise<Record<string, any>>;
* handleServerLoad: import('types').HandleServerLoad;
* }} opts
* @returns {Promise<import('types').ServerDataNode | null>}
*/
export async function load_server_data({ event, state, node, parent }) {
export async function load_server_data({ event, state, node, parent, handleServerLoad }) {
if (!node?.server) return null;

let done = false;
Expand All @@ -40,9 +41,9 @@ export async function load_server_data({ event, state, node, parent }) {
disable_search(url);
}

const result = await node.server.load?.call(null, {
const load_event = {
...event,
fetch: (info, init) => {
fetch: (/** @type {URL | RequestInfo} */ info, /** @type {RequestInit | undefined} */ init) => {
const url = new URL(info instanceof Request ? info.url : info, event.url);

if (DEV && done && !uses.dependencies.has(url.href)) {
Expand Down Expand Up @@ -112,7 +113,11 @@ export async function load_server_data({ event, state, node, parent }) {
}
}),
url
});
};

const result = node.server.load
? await handleServerLoad({ event: load_event, resolve: node.server.load })
: null;

const data = result ? await unwrap_promises(result) : null;
if (__SVELTEKIT_DEV__) {
Expand Down Expand Up @@ -140,6 +145,7 @@ export async function load_server_data({ event, state, node, parent }) {
* server_data_promise: Promise<import('types').ServerDataNode | null>;
* state: import('types').SSRState;
* csr: boolean;
* handleLoad: import('types').HandleLoad;
* }} opts
* @returns {Promise<Record<string, any | Promise<any>> | null>}
*/
Expand All @@ -151,15 +157,16 @@ export async function load_data({
server_data_promise,
state,
resolve_opts,
csr
csr,
handleLoad
}) {
const server_data_node = await server_data_promise;

if (!node?.universal?.load) {
return server_data_node?.data ?? null;
}

const result = await node.universal.load.call(null, {
const load_event = {
url: event.url,
params: event.params,
data: server_data_node?.data ?? null,
Expand All @@ -168,7 +175,9 @@ export async function load_data({
setHeaders: event.setHeaders,
depends: () => {},
parent
});
};

const result = await handleLoad({ event: load_event, resolve: node.universal.load });

const data = result ? await unwrap_promises(result) : null;
if (__SVELTEKIT_DEV__) {
Expand Down
6 changes: 4 additions & 2 deletions packages/kit/src/runtime/server/page/respond_with_error.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ export async function respond_with_error({
event,
state,
node: default_layout,
parent: async () => ({})
parent: async () => ({}),
handleServerLoad: options.hooks.handleServerLoad
});

const server_data = await server_data_promise;
Expand All @@ -57,7 +58,8 @@ export async function respond_with_error({
resolve_opts,
server_data_promise,
state,
csr
csr,
handleLoad: options.hooks.handleLoad
});

branch.push(
Expand Down
17 changes: 17 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,23 @@ export interface HandleClientError {
(input: { error: unknown; event: NavigationEvent }): MaybePromise<void | App.Error>;
}

/**
* The `handleLoad` hook runs every time a universal `load` function (for example from +page.js) is called.
* This hook can be registered on the client as well as on the server side.
* This hook provides the load `event` and a `resolve` function to call the actual hook with the event.
*/
export interface HandleLoad {
(input: { event: LoadEvent; resolve: Load }): ReturnType<Load>;
}

/**
* The `handleServerLoad` hook runs every time a server-only `load` function (for example from +page.server.js) is called on the server.
* This hook provides the server load `event` and a `resolve` function to call the actual hook with the event.
*/
export interface HandleServerLoad {
(input: { event: ServerLoadEvent; resolve: ServerLoad }): ReturnType<ServerLoad>;
}

/**
* The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering)
*/
Expand Down
7 changes: 6 additions & 1 deletion packages/kit/types/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import {
SSRManifest,
HandleFetch,
Actions,
HandleClientError
HandleClientError,
HandleLoad,
HandleServerLoad
} from './index.js';
import {
HttpMethod,
Expand Down Expand Up @@ -94,10 +96,13 @@ export interface ServerHooks {
handleFetch: HandleFetch;
handle: Handle;
handleError: HandleServerError;
handleLoad: HandleLoad;
handleServerLoad: HandleServerLoad;
}

export interface ClientHooks {
handleError: HandleClientError;
handleLoad: HandleLoad;
}

export interface Env {
Expand Down