expressjsHow do I set a cookie using Express.js?
Using Express.js, you can set a cookie with the res.cookie()
method. This method takes two parameters: the name of the cookie and an object containing the options for that cookie.
Example code
res.cookie('name', 'value', {
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
httpOnly: true,
sameSite: 'Strict'
});
This code will set a cookie named name
with the value value
that will expire in 7 days, is only available over HTTP, and is set with the Strict
sameSite option.
Code explanation
res.cookie('name', 'value', {
- this is the method that sets the cookie, with the name and value of the cookie as the first two parametersmaxAge: 1000 * 60 * 60 * 24 * 7
- this is the option that sets the cookie to expire in 7 dayshttpOnly: true
- this option sets the cookie to only be available over HTTPsameSite: 'Strict'
- this option sets the cookie with theStrict
sameSite option
Helpful links
More of Expressjs
- How can I use Express.js and Vite together for software development?
- How do I write unit tests for ExpressJS?
- How do I use adm-zip with Express.js?
- How can I create a quiz using Express.js?
- How can I use express-zip js to zip and download files?
- How can I use Express.js to make an XHR request?
- How do I use the expressjs urlencoded middleware?
- How can I use Express.js to yield results?
- How can I use OpenTelemetry with Express.js?
- How do I use Express.js to parse YAML files?
See more codes...