Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Express not using middleware

I've encountered some strange behaviour, by using middleware on my express backend. I try to use the action middleware function before my invalidJsonDetection middleware function in index.js. If I destructure my action middleware function it is not working as expected, but if I assign the middleware function with middleware.general.action it is working as intended.

file 1: middleware.js

const middleware = {};

middleware.general = {
  action(req, res, next) {
    req.action = req.originalUrl; // simple task
    next();
  }
};
middleware.security = {
  invalidJsonDetection(err, req, res, next) {
    if (err instanceof SyntaxError && err.status === 400) {
      // with destructuring: req.action === undefined
      // without: req.action === req.originalUrl  
      res.json({ action: req.action, status: 'error' });
      return;
    }
    next();
  }
};

export default middleware;

file 2: index.js

import middleware from './middlewares/middleware.js';
const { action } = middleware.general;
const { invalidJsonDetection } = middleware.security;

const app = express();

// general middleware section
app.use(cors({ origin: 'http://localhost:8080', credentials: true }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(action); // not working
// app.use(middleware.general.action); // working
app.use(invalidJsonDetection); // working as expected

app.post('/', (req, res, next) => { 
  res.json({ status: 'test' }); 
  return; 
});

app.listen(8081, () => {
  console.log(`Backend is listening on port 8081`);
  initDatabase();
});

Maybe someone could help me with this.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!