I created a "send" endpoint to write a cookie and a "get" endpoint to revise cookie value.
const express = require("express")
const app = express()
const cookieParser = require("cookie-parser")
app.use(cookieParser())
app.get("/send", (req, res) => {
res.cookie("test", "send")
res.sendStatus(200)
})
app.get("/get", (req, res) => {
console.log("request cookies: ", req.cookies)
// res.clearCookie("test") <=============== if uncomment this line
res.cookie("test", "get")
res.sendStatus(209)
})
app.listen(3500, () => console.log(`listening on port ...`))
It worked well. Then I uncomment the "res.clearCookie("test")". IMO, It should achieve the same effect. However, the response got 2 cookies instead of 1. I just cleared the value of cookie "test", and gave it a new value "get" immediately. I could not figure out why 2 "test" cookies came out.
I use express js and thunder client extension in vs code.
Then I uncomment the "res.clearCookie("test")". IMO, It should achieve the same effect.
No. When you use this res.clearCookie("test")
it instructs to delete the cookie
by setting the cookie's expiration date to a time in the past and generates a Set-Cookie
header with the name test
, no value
, and an expired-date
. And that is what you are getting.
This is how cookies
are handled when you clear and immediately set them in the same response.
So basically when you use res.clearCookie("test")
to delete cookie it generates Set-Cookie
with no-value and a time in past(01 Jan 1970 00:00:00 GMT
).Similarly when you set a new value to the same cookie(test=get)
it genarte another Set-Cookie
header with the newly added value.
That is why you are getting two cookie(one for deleted one & one for the newly set value).
I hope this explanation will help yo to understand how cookie
works internally.