Skip to content

How to intercept all requests in Express + Node.js?

In this quick post, you will learn how to intercept all requests in Express.js. Learn how to write an interceptor function to intercept all requests.

Advertisements

You can use the following block of code in index.js or app.js when you are initializing your express APIs and routes. app.use(“*” is the key here. It intercepts all requests.

app.use("*", function(req, res, next){
  let token = req.headers['authorization'] || req.headers['x-access-token']
  if(token && token.startsWith("Bearer ")){
      token = token.slice(7, token.length)
      jwt.verify(token, jwtKey, (err, decoded) => {
        if(err){
            res.status(401).json({
                error : "Token invalid"
            })
        } 
        else {
           next()
        }
      }) 
  } else {
      res.status(400).json({
          error : "Token missing"
      })
  } 
 })

I wanted to intercept all API requests and validate if the requests have JWT Bearer Token and if not, it would throw error saying Token Missing. After intercepting all requests, it would propagate to the next chain method.

Advertisements

If you want to skip a request path from interception, you can use req.originalUrl and return the req to the next chain. Here I do not want token validation for the /login call.

app.use("*", function(req, res, next){
  if ( req.originalUrl == '/api/login') return next();
  let token = req.headers['authorization'] || req.headers['x-access-token']
  if(token && token.startsWith("Bearer ")){
      token = token.slice(7, token.length)
      jwt.verify(token, jwtKey, (err, decoded) => {
        if(err){
            res.status(401).json({
                error : "Token invalid"
            })
        } 
        else {
           next()
        }
      }) 
  } else {
      res.status(400).json({
          error : "Token missing"
      })
  } 
 })
See also  Update an Excel file in node.js

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.