setting up a middleware in router.route() in nodejs (express)

Express routers have a neat use() function that lets you define middleware for all routes. router.use('/xxxxx', authorize); router.post('/xxxx', 'xxxx'); should work.


Middleware:
sampleMiddleware.js

export const verifyUser = (req, res, next) => {
   console.log('Verified')
   next();
}

Routes

import express from 'express';
import { verifyUser } from './sampleMiddleware.js';

const userRoutes = express.Router();

userRoutes.route('/update').put(verifyUser, async function(){
     //write your function heere
});

Define a middlware function before you define / include your routes, this will avoid you checking for a valid session in every route. See code below for an example on how to do this.

If some routes are public, i.e. they do not require a user to have a valid session then define these BEFORE you 'use' your middlware function

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

//This is the middleware function which will be called before any routes get hit which are defined after this point, i.e. in your index.js
app.use(function (req, res, next) {

  var authorised = false;
  //Here you would check for the user being authenticated

  //Unsure how you're actually checking this, so some psuedo code below
  if (authorised) {
    //Stop the user progressing any further
    return res.status(403).send("Unauthorised!");
  }
  else {
    //Carry on with the request chain
    next();
  }
});

//Define/include your controllers

As per your comment, you have two choices with regards to having this middleware affect only some routes, see two examples below.

Option 1 - Declare your specific routes before the middleware.

app.post("/auth/signup", function (req, res, next) { ... });
app.post("/auth/forgotpassword", function (req, res, next) { ... });

//Any routes defined above this point will not have the middleware executed before they are hit.

app.use(function (req, res, next) {
    //Check for session (See the middlware function above)
    next();
});

//Any routes defined after this point will have the middlware executed before they get hit

//The middlware function will get hit before this is executed
app.get("/someauthorisedrouter", function (req, res, next) { ... });

Option 2 Define your middlware function somewhere and require it where needed

/middleware.js

module.exports = function (req, res, next) {
    //Do your session checking...
    next();
};

Now you can require it wherever you want it.

/index.js

var session_check = require("./middleware"),
    router = require("express").Router();

//No need to include the middlware on this function
router.post("/signup", function (req, res, next) {...});

//The session middleware will be invoked before the route logic is executed..
router.get("/someprivatecontent", session_check, function (req, res, next) { ... });


module.exports = router;

Hope that gives you a general idea of how you can achieve this feature.