DEV Community


How to use cookies?

・1 min read

I want to send a cookie from the svelte server to the client. I have tried the following simple steps:

The page m.svelte:

  const callm = async () => {
    const response = await fetch("/m", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      body: JSON.stringify({ somedata: "abc"})
    const r = await response.json();
    await console.log("Response", r);
    await console.log("Cookie", document.cookie);

<button on:click={callm}>M</button>

And the server route m.js:

export async function post(req, res) {

  const { somedata } = req.body;
  res.writeHead(200, {
    'Set-Cookie': `my1cookie=${somedata};Max-Age=60`,
    'Content-Type': 'application/json'
  res.end(JSON.stringify({ somedata }));  // thats is only a test

What I expect: when I press the M button, data is sent to the server and returned as a cookie.
The cookie arrives as I checked with the Chrome Inspector, but is not displayed with console.log

What have I done wrong?

Discussion (1)

hasssanezzz profile image
hasssanezzz • Edited

did you find a fix ??
I know it's been a year but I have the same issue and I can't find a solution