Reputation: 127
I am running a small node app. And I am trying to get it to create a cookie for each visitor, called 'session' that contains - for example - the session id. But I cannot seem to get node to create a cookie through cookie-session. My code so far:
const fs = require('fs');
const http = require('http');
const https = require('https');
const privateKey = fs.readFileSync('PATHTOKEY');
const certificate = fs.readFileSync('PATHTOKEY');
const credentials = {key: privateKey, cert: certificate};
const Keygrip = require("keygrip");
const express = require('express');
const app = express();
const port = APORTNUMBER;
const secureport = APORTNUMBER;
const helmet = require('helmet');
const options = {
dotfiles: 'deny',
etag: true,
extensions: ['html', 'htm'],
index: 'index.html',
lastModified: true,
maxAge: 0,
redirect: true,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
};
app.use(express.static('public', options), helmet());
So far, no problems. But then comes the middleware cookie-session.
const session = require('cookie-session');
const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
app.use(
session({
name: 'session',
keys: new Keygrip(["MYSECRET1", "MYSECRET2"]),
cookie: {
secure: true,
httpOnly: true,
expires: expiryDate
}
})
);
Above, I've specified the middleware to use these cookie-session parameters, but how do I proceed from here to actually get it to create this cookie?
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);
httpServer.listen(port);
httpsServer.listen(secureport);
console.log("Node server started");
Upvotes: 0
Views: 4394
Reputation: 6914
Well, after trying this myself I manages to successfully use the cookie-session
middleware. yay
I'm using the middleware like this:
app.use(cookieSession({
name: 'session', // replace this with your own name to suit your needs
keys: [ 'your-secret-key-goes-here', 'your-secret-key-goes-here' ]
})
About the duplicate values in keys
option - the docs and related examples always use 2 different keys, despite the TypeScript @types
lib declares that
The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.
So.. I've used only one key.. twice... and it works as excepted
Note that I'm using this middleware before I'm registering the express app
routes in order for this middleware to take effect before the router is executed (per request)
In each of my routes I can use the middleware using something like this
app.get('/test', (req, res) => {
req.session.test = { a: 5, b: 7} // yes - JSON payload are valid :)
})
To verify - ensure that your initial request got the following headers
Set-Cookie: session=eyJ0ZXN0Ijp7ImEiOjUsImIiOjd9fQ==; path=/; secure; httponly
Set-Cookie: session.sig=D4VVF4XSbBEWXI4b04ZvybAxppw; path=/; secure; httponly
This is only an example where the session
is the name of the cookie as I've defined earlier. Cheers
Upvotes: 2
Reputation: 127
I've not been able to figure out how to work with neither express-cookie nor cookie-session. However, I have been able to create cookies with cookie-parser middleware.
dependency:
const cookieParser = require('cookie-parser');
config:
const cookieConfig = {
httpOnly: true,
secure: true,
maxAge: 1800,
signed: true
};
Express:
app.use(cookieParser('MYSECRET'));
app.use(function (req, res, next) {
let cookie = req.cookies.cookieName;
if (cookie === undefined) {
let randomNumber=LOGICFORRANDOMNUMBER
res.cookie('COOKIENAME', randomNumber, cookieConfig);
};
next();
});
Upvotes: 0
Reputation: 25725
Your current code looks right, based also on the documentation @ http://expressjs.com/en/resources/middleware/cookie-session.html
I would suggest defining an app.get
and testing everything with a tool like postman or fidler.
e.g.
app.get('/test', function (req, res, next) {
// Update views
req.session.views = (req.session.views || 0) + 1
// Write response
res.end(req.session.views + ' views')
})
Upvotes: 0