We are usually protecting routes which shouldnt be accessible for not logged users, for example orders, cart, … We can use our own middleware for this.



Prerequisities

We have some login page, we have default authenticate system, user will enter email and password, app will look into db, if there is that user with email and password, it will set req.session.isLoggedIn = true;. We are using sessions which are stored in db and we are using mongoose.



middleware/is-auth.js

If somebody wants to visit protected route, we redirect him to login page.

module.exports = (req, res, next) => {
    if (!req.session.isLoggedIn) {
        return res.redirect('/login');
    }
    next();
}



routes/shop.js

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

const shopController = require('../controllers/shop');
const isAuth = require('../middleware/is-auth');

router.post('/cart', isAuth, shopController.postCart);



controllers/shop.js

exports.postCart = (req, res, next) => {
    //code which will add product to cart
}