Problem
Cookies in happy-dom/jsdom virtual DOM are not set based on set-cookie response header.
Context
I’m testing my API with Vitest and happy-dom.
First of all I fetch POST /api/auth/login endpoint and I get response with set-cookie header
Then I fetch POST /api/auth/logout where Authorization cookie should be sent.
- POST /api/auth/login
const response = await fetch('http://localhost:3000/' + 'api/auth/login', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ code: sendEmailTextContent, email: generatedOwnerEmail })
});
response.getSetCookie()
method return value
[
'Authentification=eyJhbGdcCI6IkpXVCJ9.eyJpsasgdZCI6IjdjMGRhYTAwLThiNjEtNDc1NS05ZjQ2LWY4NTQ3NmM1ODVkZSIsImlhdCI6MTcyNjYwMDY4MywiZXhwIjoxNzI2Njg3MDgzfQ; Max-Age=21600; Path=/',
'Refresh=5sdfsdfsassdf.IjdjMGRhYTAwLThiNjEtNDc1NS05ZjQ2LWY4NTQ3NmM1ODVkZSIsImlhdCI6MTcyNjYwMDY4M30.ssdsAsf3d3gsasdfas44tscvvsg; Max-Age=604800000; Path=/api/auth/refresh-token'
]
API responds with proper cookies.
- DELETE /api/auth/logout
const response = await fetch('http://localhost:3000/' + 'api/auth/logout', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
I get AccessTokenInvalid
error and when logging cookie from request, on API, I get undefined. There is no Cookie header in logout request.
What I tried
- I set proper url in happy-dom/jsdom config – http://localhost:5173 – my frontend port, works with my API CORS
- I tried logging
document.cookies
, it’s always empty - I tried to manually setting cookies in
document.cookie
, worked but when fetching DELETE /api/auth/logout Cookie header was not automatically set to proper value - I tried changing
happy-dom
tojsdom
with cookieJar option set to true, didn’t work - I tried manually saving and retrieving cookies from Cookie Jar used by jsdom, worked but this is not what I want. It should be handled automatically like browser does (yes, my api and cookies work proper on real browser, so it happens only in testing environment)
- I’ve read happy-dom and jsdom docs, jsdom docs say that cookies are saved automatically in cookie jar based on set-cookie header
What am I doing wrong?
PoProstu Kamil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1