I am working on express/node.js and trying to understand cookies of expressjs and I'm setting cookie like this:
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/', function(req, res){
res.cookie('cookie1', 'This is my first cooke', {maxAge: 1000*60*60*24*7, httpOnly: true});
res.end('Cookie has been set');
});
And accessing cookies as follows:
app.get('/readCookies',function(req, res){
res.send(req.cookies.cookie1);
});
But the problem is signed: true
option when including this one for encoding cookie value during setting the cookie I am getting the following error:
Error: cookieParser("secret") required for signed cookies
Please help me and thanks in advance
The error is explaining what you need to do to be able to send signed cookies:
Error: cookieParser("secret") required for signed cookies
The Express documentation states:
When using
cookie-parser
middleware, this method also supports signed cookies. Simply include thesigned
option set totrue
. Thenres.cookie()
will use the secret passed tocookieParser(secret)
to sign the value.
The cookie-parser
documentation states:
cookieParser(secret, options):
secret
a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret.
So everything combined:
install cookie-parser
middleware:
npm install cookie-parser
add it to the Express app:
const cookieParser = require('cookie-parser');
...
app.use(cookieParser('MY SECRET'));
make it sign cookies:
res.cookie('cookie1', 'This is my first cookie', { signed : true });
and read the cookie value back:
res.send(req.signedCookies.cookie1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With