Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Hooks: hooks.server.js

A hook is a function that SvelteKit calls at a certain stage of its work for all requests at once. Hooks do what every page needs: identify the user by a cookie, log requests, add headers. Server hooks live in the src/hooks.server.js file.

The handle hook

Create the file src/hooks.server.js and export a handle function:

// src/hooks.server.js
export async function handle({ event, resolve }) {
  const start = Date.now();
 
  const response = await resolve(event);
 
  console.log(`${event.request.method} ${event.url.pathname} — ${Date.now() - start} ms`);
  return response;
}

handle receives the request event and the resolve function, which builds the normal response — a page or the result of +server.js. Open a few pages of the site: the terminal where npm run dev runs shows lines like GET /blog — 12 ms.

event.locals

A hook can put data into the event.locals object. It is available in all load functions, actions and +server.js for that request:

// src/hooks.server.js
export async function handle({ event, resolve }) {
  const name = event.cookies.get('author');
  event.locals.author = name ?? 'Guest';
 
  return resolve(event);
}

Now any server function knows the author of the current request:

// src/routes/blog/new/+page.server.js (next to actions)
export function load({ locals }) {
  return { author: locals.author };
}

On the /blog/new page the value is available as data.author: while there is no author cookie, it is "Guest". This is how a logged-in user is usually passed on after checking the session in a hook.

Answering without a page

handle can answer by itself without calling resolve. For example, to close a section for maintenance:

// src/hooks.server.js
export async function handle({ event, resolve }) {
  if (event.url.pathname.startsWith('/admin')) {
    return new Response('This section is temporarily closed', { status: 503 });
  }
  return resolve(event);
}

Any address starting with /admin returns the text with code 503.

The handleError hook

The handleError function in the same file is called on an unexpected error — an exception in load or in a component:

// src/hooks.server.js
export function handleError({ error, event }) {
  console.error('Error at', event.url.pathname, error);
  return { message: 'Something went wrong' };
}

The full error goes to the server log, while the visitor sees only the safe message from the returned object. Errors raised with error(404, ...) are considered expected and do not reach this hook.

Common mistake

Forgetting to return the result of resolve(event). If handle returns nothing, no page of the site opens — SvelteKit reports that the hook did not return a response. The last line of handle must be return resolve(event) or return response.

Thanks for reading!

Donate to the site — we work hard for you.