4

I am trying to extract the value of a cookie in sveltekit that is recieved from the backend but i cannot seem to find a way to access cookies in svelte also i am using Typescript and if possible i don't want to access the DOM directly.

So far i've tried using:

  • js-cookie
  • chatGPT anwear that was totally incorrect
  • Le internet which hasn't worked since i am asking right here

The set-cookie header is shown in the network tab it isn't secure nor it is httponly. Just please explain how i can access it's value from sveltekit typescript.

EDIT: backend is actix-web

Solved: I set the domain to localhost on the actix side and also set the cookie to secure.

2
  • The more important question is: Why?
    – brunnerh
    Commented Dec 19, 2022 at 16:43
  • are you using sveltekit purely as frontend ? like with a static adapter or do you have a server part as well ? Commented Dec 20, 2022 at 6:39

1 Answer 1

5

I assume when you say backend you mean the backend written with SvelteKit, since SvelteKit is a Full-Stack-Framework.

The way you do this in SvelteKit is by writing your cookie logic inside a server load function:

import * as db from '$lib/server/database';
import type { LayoutServerLoad } from './$types';
 
export const load = (async ({ cookies }) => {
  const sessionid = cookies.get('sessionid');
 
  return {
    user: await db.getUser(sessionid)
  };
}) satisfies LayoutServerLoad;

You can do the same for cookies.set(…).


If you want to access the Cookie value from your client side svelte component, you can pass it via the server load function into the data you can access in your component.

+page.server.ts

import type { PageServerLoad } from './$types';

export const load = (async ({ cookies }) => {
  const tastyCookie = cookies.get('tastyCookie');

  return {
    tastyCookie
  };
}) satisfies PageServerLoad;

+page.svelte

<script lang="ts">
  import type { PageData } from './$types';

  export let data: PageData;
</script>

<h1>{data.tastyCookie}</h1>

I think you should also be able to access the cookie string from inside the onMount hook on your client svelte page, but I would strongly recommend going with the above shown methods, since this is the Kit way of doing things.

4
  • Sorry for not specifing that the backend is written in actix web and it send a cookie to the frontend(svelte)
    – Snek
    Commented Dec 19, 2022 at 17:27
  • When I tried this, +page.server.ts throws a TypeError: Cannot read properties of undefined (reading 'get'). The only place I see the cookie I want picked by the server is in hooks.server.ts
    – rob_hicks
    Commented Feb 8, 2023 at 16:03
  • @rob_hicks maybe you need to update to a newer SvelteKit version, e.g. "^1.11.0"
    – Tobi Obeck
    Commented Mar 20, 2023 at 0:40
  • This doesn't run for the root url, runs find for other urls though :-/ Commented Aug 20, 2023 at 7:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.