Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Accessing a cookie in the universal load function (+page.js) when using SvelteKit

Stanislav KhromovStanislav Khromov

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.

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.