A tip was recently shared by Patrick in the Svelte Discord around how you can get around the fact that you can’t access cookies in universal load functions. Here is the example code:
// src/hooks.server.js
export function handle({ event, resolve }) {
if (event.route?.id === '/my-path') {
event.params.__MY_COOKIE__ = event.cookies.get('my-cookie');
}
return resolve(event);
}
// src/routes/my-path/+page.js
export function load(event) {
if (browser) {
// get cookies from `document.cookie`
} else {
// use `event.params.__MY_COOKIE__`
}
}
Keep in mind this relies on a hack (adding data to event.params
) and could stop working in the future, and it likely can’t work with cookies marked HttpOnly. It’s generally best to fetch the cookie in +page.server.js
and send it up to the universal load function instead.