To set cookies in Node apps that use the Express web framework, we can use the res.cookie
method to set the cookie.
res.cookie
will be available once we add the cookie-parse
package into our app, which we can install by running:
npm i cookie-parser
For instance, we can write:
const express = require('express')
const cookieParser = require('cookie-parser');
const app = express()
const port = 3000
const options = {
maxAge: 1000 * 60 * 15,
httpOnly: true,
signed: true
}
app.use(cookieParser('secret'));
app.get('/', (req, res) => {
res.cookie('cookieName', 'cookieValue', options)
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We add:
app.use(cookieParser('secret'));
to add the cookieParser
middleware.
The argument is the secret.
Then to add the cookie to the response of the /
route, we call res.cookie
with the cookie key, value, and options respectively.
maxAge
is the duration that the cookie lasts.
httpOnly
set to true
makes the cookie accessible only by the webserver.
signed
set to true
indicates that the cookie should be signed with a secret.
Now when we make a request to the /
route, we get the cookie back in the response.