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 do I set the time zone in Express.js?
- How do I use Yarn to add Express.js to my project?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js to yield results?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js and Winston together to create a logging system?
- How do I use Zod with Express.js?
- How can I use Express.js with TypeScript?
See more codes...