0

I want to log a user in and store there session so i can identify them. and then have some code on the back end that gets there data from and allows me to pass the username into another db method.

i have the following, but want to use session without having to add it to every page i need it on, or is that not possible?

var express = require('express');
var app = express();

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));

app.get('/awesome', function(req, res) {
  if(req.session.lastPage) {
    res.write('Last page was: ' + req.session.lastPage + '. ');
  }

  req.session.lastPage = '/awesome';
  res.send('Your Awesome.');
});

app.get('/radical', function(req, res) {
  if(req.session.lastPage) {
    res.write('Last page was: ' + req.session.lastPage + '. ');
  }

  req.session.lastPage = '/radical';
  res.send('What a radical visit!');
});
f1wade
  • 2,877
  • 6
  • 27
  • 43
  • Maybe if someone can confirm if this is how I should use Express-session, and what i need to do to keep the session alive when the user visits another webpage? – f1wade Feb 23 '16 at 11:59

2 Answers2

0

The short answer is NO.

the session will be available to all pages, but unless you add the session and its options, you wont be able to access it in your code.

so it has be put on each page that you want to use it.

f1wade
  • 2,877
  • 6
  • 27
  • 43
0

Like this?

// my-middleware.js
module.exports = function(req, res, next) {
  if (req.session.lastPage) {
    res.write('Last page was: ' + req.session.lastPage + '. ');
  }
  req.session.lastPage = req.path;
  next();
};

// app.js
app.use(express.session({secret: '1234567890QWERTY'}));
app.use(require('./my-middleware'));

app.get('/awesome', function(req, res) {
  res.send('Your Awesome.');
});

app.get('/radical', function(req, res) {
  res.send('What a radical visit!');
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • This is all in one page, I want it as middle Ware so I only have to write the code once, and is accessible in other js server side files – f1wade Mar 08 '16 at 19:50