Access Cookies in Multiple places in Sveltekit?

Getting cookie 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.

svelte logo

Want a Svelte site built?
Hire Me.

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 cookies = event.request.headers.get("cookie");
  const parsedCookies = parse(cookies || "");
  //do something with cookies

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

Access cookies in getSession

You can use this snippet if you want to set a cookie in the session object.

import { parse } from "cookie";

export const getSession = ({ request }) => {
  const cookies = request.headers.get("cookie");
  const parsedCookies = parse(cookies || "");

  return {
    cookies: parsedCookies,
  };
};

Whatever is returned from this function is set as session. You can access this in the component mentioned below.

Access cookies in the Load function

To access cookies from the load function, you should first set the cookies in getSession as mentioned in the above method.

Once it is set, you can access the cookies this way.

<script context="module">
  export const load = ({ session }) => {
    // session is cookies!
    return {
      props: {
        session,
      },
    };
  };
</script>

<script>
  export let session;
  // you can get it into DOM if needed
</script>

Access cookies in DOM

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.

For this to work, you should first set the cookies in getSession as mentioned in the above method.

Once it is set, you can get the cookies like this

<script>
  import { session } from "$app/stores";
  console.log($session)
  // here $session will have the cookies
</script>

Access cookies in Endpoints

Endpoints have a request object from which we can parse the cookies as shown below.

import { parse } from "cookie";

export const get = async ({ request }) => {
  const cookies = request.headers.get("cookie");
  const parsedCookies = parse(cookies || "");

  return {
    body: parsedCookies,
  };
};

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

Demo

Sveletkit Access Cookies

Find related articles

Let's discuss on Twitter