Access Cookies in Multiple places in Sveltekit?

Getting cookies from a request in Sveltekit can be tricky. I have shown different ways to do it in hooks, endpoints, load function, and the component DOM itself.

Updated

This applies to the latest sveltekit.

Let’s see how we can access browser cookies in Sveltekit.

Access cookies in the hooks.js file

This is usually the first place where we can access cookies. You might want to install the cookie package to parse the cookies into objects.

Access cookies in the handle function

import { parse } from "cookie";

export async function handle({ event, resolve }) {
  const sampleCookie = event.cookies("sampleCookie");
  //do something with cookies

  const response = await resolve(event);
  return response;
}

Access cookies in the layout server load function

Here is how you can access cookies from the +layout.server.js, or +page.server.js file

+layout.server.js / +page.server.js

export const load = async ({ cookies }) => {
  const sampleCookie = cookies.get("sampleCookie");

  return {
    sampleCookie, // return here so that it can be accesed by page load function
  };
};

Access cookies on the page

There is a more straightforward way to get the cookies into DOM. I don’t know why you’d want to do that but it is possible.

+page.svelte

<script>
  import { browser } from "$app/environment";
  let cookies = browser && document.cookie;
</script>

This isn’t the best way to do it. Here is how you can get the cookies into +page.svelte or any component.

You can get it through page stores which would be the way I recommend. But you should set it in +layout.svelte.js or +page.server.js

+page.svelte

<script>
  import { page } from "$app/stores";

  console.log($page.data.cookies);
</script>

Access cookies in page load function

Endpoints can get cookies if they are passed from a parent server file.

We are passing cookies in our +layout.server.js. So this will be our parent now.

You can do this in your +page.js file

page.js

export const load = async ({ parent }) => {
  const data = await parent();
  console.log(data.sampleCookie);
  // this will print out sampleCookie returned by server load function
  return {};
};

Now, this is not limited to cookies. Anything in the request that should go to the sveltekit endpoints, load function, or components can be done this way.

Find related articles

Let's discuss on Twitter