Express by Examples
Session with File Storage
This chapter will describe how to use 'express-session' middleware to authenticate login in NodeJS (ExpressJS).
Visit https://github.com/expressjs/session .
Here will be described File Session Storage.
Installation
$ npm install --save express-session
$ npm install --save session-file-store -for creating session files
Integration into ExpressJS
Add into /app.js file:
var session = require('express-session');
var FileStore = require('session-file-store')(session);
//file session
var sess_options = {
path: "./tmp/sessions/", //directory where session files will be stored
useAsync: true,
reapInterval: 5000,
maxAge: 10000
};
app.use(session({
store: new FileStore(sess_options),
secret: 'my_secret_key',
resave: true,
saveUninitialized: false
}));
Notice: If saveUninitialized is false then session file is not created unless we set req.session.username='val' . Also session file is deleted on req.session.destroy();
If it is true then session file is created each time we run ./app.js file, e.g. each time we run in broweser any page http://localhost:3000 . Also session file is not deleted after we apply req.session.destroy();
Also add admin route to enable access admin area by http://localhost:3000/admin/
var admin = require('./routes/admin/index');
app.use('/admin', admin);
The complete /app.js file will be:
/*jslint unparam: true*/
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//session
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var routes = require('./routes/index');
var admin = require('./routes/admin/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//session
var sess_options = {
path: "./tmp/sessions/",
useAsync: true,
reapInterval: 5000,
maxAge: 10000
};
app.use(session({
store: new FileStore(sess_options),
secret: '2015tajnikljuc',
resave: true,
saveUninitialized: true
}));
app.use('/', routes);
app.use('/admin', admin);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Now you can get or set session variable by ‘req.session‘. Just like we do in PHP using $_SESSION variable.
So create /router/admin/index.js
/*jslint unparam: true*/
var express = require('express');
var router = express.Router();
var nodedump = require('nodedump').dump;
/* Set session */
router.get('/set', function (req, res, next) {
req.session.username = 'nesto';
res.send('Session is set: ' + req.session.username);
});
/* Get session */
router.get('/get', function (req, res, next) {
res.send(nodedump(req.session.username));
});
module.exports = router;
Conclusion:
1. Session file is stored into /tmp/sessions/TOBytIuyqPWFx4tW3BIS8s6O6dtcVXlg.json file
{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"__lastAccess":1429970672649,"username":"nesto"}
2. To set session value use simple: req.session.var = ' value ';
3. To get session variable use: req.session.var;
Other Session Storages
Besides session-file-store there are many other session storages:
- connect-mongo
- connect-redis
- connect-marklogic