Writing the sessionCheck middleware

The next step is to create our middleware function that does a session check.

As of ExpressJS Version 4.x, all the middleware, except static, have been removed and need to be installed and included as needed. Thus, we download our session module with the following terminal command:

npm install express-session --save

We then include the following lines in the respective sections of our app.js file:

var session = require('express-session');
app.use (session());

Next, we write our function that will check the user sessions. We add this to the api.js file:

function sessionCheck(request,response,next){

    if(request.session.user) next();
        else response.send(401,'authorization failed');

Now, to secure the API routes, we simply need to call the sessionCheck function after the route name, as highlighted in the following code:

router.post('/pages/add', sessionCheck, function(request, response) {

Usually, we’d want to secure the APIs that modify the data, and hence, we will add the sessionCheck function to the add, update, and delete APIs as follows:

  • For the update API, it should be as follows:
    router.post('/pages/update', sessionCheck, function(request, response) {
  • For the delete API, it should be as follows::
    router.get ('/pages/delete/:id', sessionCheck, function(request,response){
  • For the details API, it should be as follows::
    router.get('/pages/admin-details/:id', sessionCheck, function(request, response) {