Trouble arises when attempting to transfer cookies between server in Fastify and application in Svelte Kit

In the process of developing a web application, I am utilizing Fastify for the backend server and Svelte Kit for the frontend. My current challenge lies in sending cookies from the server to the client effectively. Despite configuring Fastify with the @fastify/cookie plugin and enabling CORS handling using the @fastify/cors package, the cookies do not seem to be transmitted correctly to the client when a request is made.

Here's how I have set up the CORS and cookie handling on my Fastify server:

import Fastify from "fastify";
import cors from "@fastify/cors";
import fastifyCookie from "@fastify/cookie";

const fastify = Fastify();

fastify.register(cors, {
  origin: process.env.CORS_ORIGIN,// value: CORS_ORIGIN=http://localhost:5173
  credentials: true,
  allowedHeaders: ["Content-Type", "Authorization"],
  maxAge: 600,
  exposedHeaders: ["*", "Authorization"],
});

fastify.register(fastifyCookie, { secret: process.env.COOKIE_SECRET /* COOKIE_SECRET=cloudhub */ });

// ...
// ....

async onSubmit(values, helpers) {
  const request = await fetch(`http://127.0.0.1:7878/api/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(values),
  });

  //....
}

Upon investigating on the server, it appears that the cookie is properly set in the response by examining the headers, which include the following:

// general
Request URL: http://127.0.0.1:7878/api/auth/login
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:7878
Referrer Policy: strict-origin-when-cross-origin

// response headers:
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:5173
access-control-expose-headers: *, Authorization
Connection: keep-alive
content-length: 299
content-type: application/json; charset=utf-8
Date: Sun, 04 Jun 2023 23:00:49 GMT
Keep-Alive: timeout=72
set-cookie: accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Ijg3ZDkjK2YyNjkBmbjfEjAyzfM5QlzIXtbCMahtb4ylHzNm64312lcmci3kvmwyDoEi");
vary: Origin

// request headers

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es;q=0.8
Connection: keep-alive
Content-Length: 50
Content-Type: application/json
Host: 127.0.0.1:7878
Origin: http://localhost:5173
Referer: http://localhost:5173/
sec-ch-ua: "Brave";v="113", "Chromium";v="113", "Not-A.Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Sec-GPC: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

However, despite the server-side confirmation, the Network tab in the browser does not display the sent cookie information.

If you have any insights or recommendations on how to ensure proper transmission of cookies between the client and server, your assistance would be highly valued. Thank you!

Answer №1

When utilizing an API to transmit a cookie, the cookie will be visible in the response cookie instead of the header.

For reference, refer to the code snippet provided below:

response.setCookie('myCookie', "yyyyyyyy", {
    domain: 'example.com',
    path: '/',
    signed: true
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

error: unexpected token } in Node.js syntax

I am struggling to identify my issue! /var/www/html/bot# nodejs driver /var/www/html/bot/driver.js:2239 }); ^ SyntaxError: Unexpected token } at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._co ...

When implementing a Vue component, you may encounter a 'parentNode' TypeError

I'm experiencing an issue with a page that is only partially rendering. Specifically, the page renders Listings but not Bookings. After some investigation, I discovered that removing the divs associated with isReviewed() resolves the rendering issue. ...

I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted. The current error code I am encountering is: I initially suspe ...

What methods are available for drawing on an HTML canvas using a mouse?

I am facing two challenges: how can I create rectangles using the mouse on an HTML canvas, and why is my timer not visible? Despite trying various code snippets, nothing seems to be working. Grateful for any help! HTML: <!DOCTYPE html> <html lan ...

Selecting a directive's scope

Though the title may not capture it quite accurately, I struggled to find a more fitting description. I crafted a directive that incorporates an ng-repeat: app.directive('appDirective', function($purr){ var template = '' + ...

The chai property "matchSnapshot" is not valid

After following the instructions provided at this link, I am now in the process of writing basic Jest tests for my React application that uses the Create-React-App starter kit. I came across a recommendation mentioned here that advises against installing ...

A helpful guide on passing a component as a prop to a child class and incorporating it within the child component along with additional props

Within my parent class, I have loaded a child class component and passed another component to it as a prop. In the childclass component, I am trying to display that component. <EditRecordModal show={this.state.showEditModal} onHide={this.handle ...

Is there a reason why angularJS doesn't provide the exact error location directly, opting instead to just offer a link to their website that provides a generic explanation?

Why does AngularJS not provide the specific error location directly, such as which file the error is in, instead of just giving a link to their website with a generic explanation? This makes debugging very challenging! Whenever there is an error, it becom ...

Ways to dynamically display components in React Native

In my React Native app, I have a custom tab control that is rendered dynamically using the following configuration: const TABS = [ { title: 'Tab 1', component: MyComponentOne }, { title: 'Tab 2', component: MyComponentTwo } ]; T ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

Retrieve JSON data and use a button to sort and display markers on a Google Map

Is it possible to modify my function in order to use different PHP files with separate buttons without duplicating the code? Currently, I have a function that displays markers on an external HTML page when a button is clicked. The data is retrieved from fi ...

What is the best way to handle code versioning using Django, Angular2, and Webpack?

Currently, I am utilizing Django in conjunction with Angular 2 and Webpack. Within Django, I have set up a URL to display my application at http://example.com/user/beta. Initially, my index.html file is rendered, which contains my Angular 2 components. Wit ...

Revolutionary AJAX technology seamlessly updates and refreshes elements within every row or form on a webpage

<script type="text/javascript"> $(document).ready(function() { $("#submit<?php echo $resultshome['hskid']; ?>").click(function() { $.ajax({ type : "POST", url : "/scores/printPOST.php", data : { "subro ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Node.js data transmission: Sending information from server to client

In my node project, PUG/Jade files are used to render webpages. Every minute, a JS file updates a redis database and I want the GUI to reflect these changes without requiring a page refresh. Here is an overview of how the data is currently passed: User ...

When the down arrow key is pressed, the focus of the radio button is lost

I've been facing a persistent accessibility issue with the main-component in Angular. This component contains four different templates, but depending on the radio button selection, other templates are displayed. The problem arises when these templates ...

Encountered a 404 error while handling the Express 4 module, indicating that the 'html' module could not be

I need to update my express app to handle 404 (and 500) errors by displaying HTML instead of plain text. I have been able to show text to the client for 404 errors, but now I want to show HTML instead. My 404.html file is located in the /app directory. Cu ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...

Using redux alongside fela and react: A comprehensive guide

First of all, thank you for your attention. I am currently exploring the use of fela for dynamically styling my components and for managing app states, I plan to incorporate redux. In fela, it's necessary to utilize a Provider to encompass all app com ...