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!