1
**app.get('/', (req,res)=>{
    res.send('Api is running...');
})

app.use('/api/products/', productRoutes);

app.use(notFound);

app.use(errorHandler);**

Above is the gist of my code where app.use(notFound) and app.use(errorHandler) are middleware. This pattern works perfectly fine. However when i interchange the position of the command to below then there is a break in the application. are middlewares to be placed at the bottom? please help me here to clear my confusion.

**app.get('/', (req,res)=>{
    res.send('Api is running...');
})

app.use(notFound);

app.use(errorHandler); 

app.use('/api/products/', productRoutes);**
  • When you call notFound middlewear, usually it will have a logic to throw error and pass it to next(), which is errorHandler. So it will continue to execute whatever is inside erorrHandler (mostly return some error to client). So to avoid this, you need to place the router files above the errorhandlers. – Mr.Bhat May 31 '21 at 14:32

1 Answers1

0

Actually, yeah, I suggest notFound middleware sends the response and set headers, so that calling errorHandler or productRoutes leads to common error Cannot set headers after they are sent. If you define middlewares before routes — they are called first(I personally name them as 'configurable middlewares' or 'middlewares that configure my express app').

But if you define them after routes they will be called by next() function which is provided by a 'route'. next() calls the next middleware 'in a queue' after routes.

Denys Rybkin
  • 637
  • 1
  • 6
  • 18