Search code examples
node.jsexpresssessionexpress-session

ExpressJS: How to conditionally start session?


This may sound like a really simple/silly question, but I can't find anything about it on the web.

I'm using Express 4 with NodeJS and trying to implement session using express-session middleware. I want to use session to allow/disallow certain routes for different users.

I know I can use session on conditional route:

const express = require('express');
const Router = require('express').Router;
const router = new Router();

const session = require('express-session');
const sessioning = session({...});

router.post('/login', sessioning, (req, res) => {

});

But that's not what I'm trying to do. That will start a session even for failed login attempt.

What I'm trying to do is to start the session only after a successful login attempt:

const express = require('express');
const Router = require('express').Router;
const router = new Router();

const session = require('express-session');


router.post('/login', (req, res) => {

  /* ... Login validations */

  if (login === 'success'){

    /* ... start session */

  }

  res.json({...});

});

So that I can disallow unauthenticated users from protected routes:

router.get('/protected', (req, res) => {

  if (!req.session){
    res.status(401);
    res.end();
    return;
  }

  /* ... */

});

If I set session directly on protected routes, then it can't verify whether or not a user is logged in.

Can anyone point me to the correct direction?


Solution

  • This does not answer your primary question but address your (seemingly) main concern:

    If I set session directly on protected routes, then it can't verify whether or not a user is logged in.

    You can attach a variable to the req.session object to check if user is logged in.

    Set loggedIn in status in your login route

    router.post('/login', (req, res) => {
      /* ... Login validations */
      if (login === 'success'){
    
        req.session.loggedIn = true;
      }
      // ...
    });
    

    And set up a middleware that checks wether the user is logged in and protect your routes.

    function checkLoggedIn(req, res, next) {
      if (req.session.loggedIn)
        next();
      else
        res.redirect('/login')
    }
    
    // Your protected route
    router.get('/protected', checkLoggedIn, (req, res) => {
      // ...
    });