-2

I have seen these code in my project.

when 2 parameters:

app.use("*", (req: Request, res: Response) => {
});

when 3 parameters:

app.use("*", (req: Request, res: Response, next: NextFunction) => {
});

when 4 parameters:

app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => {
});

Q1) Is there any documentation on why we use err as the first param? I'm pretty confused with this approach. How many types of arguments are there!?

Q2) I need to add a header in all responses. To be more precise I need to add CSP in the response header. Should I add using a middleware approach i.e., app.use(csp); Or any suggestions.

Rex
  • 5
  • 3
  • These are express specific. Your use-case indeed should be another middleware. Just add the middleware with `use` and call `next()` after you added your headers to `response`. – Evert Sep 18 '22 at 03:30
  • thanks, @Evert. I was trying that approach. I tried to add a header using setHeader() but didn't work. Then tried spread operator res.header={...res.header,"key":"value"}. Now going to try res.append() hope it works :) – Rex Sep 18 '22 at 03:47
  • If you are still stuck, edit your question and add the code you tried. Something others can reproduce. Also learn about syntax highlighting in stack overflow so its easier for others to read your code! – Evert Sep 18 '22 at 04:19
  • What is your end goal? What are you trying to achieve? Please read [How to Ask](https://stackoverflow.com/help/how-to-ask). – WhatTheClown Sep 18 '22 at 06:10

1 Answers1

0

Question 1:

Three parameters function is actual Express Middleware, which contains

req : Request Object, res: Response Object, next: Next Function

next() function is used to transfer the current flow to next middleware. For Example, let's say we have two middlewares.

app.use((req, res, next) => {
    console.log('THis is first Middleware')
    req.nextMiddlewareValue = 'Previous Middleware value'
    /* Code flow will transfer to the next middleware, defined below */
    next()
})

app.use((req, res, next) => {
  // If we try to console te req.nextMiddlewareValue object
  console.log(req.nextMiddlewareValue)    // Previous Middleware value
})

Make sure both middlewares should be used next to another.

Four parameters function middleware, basically, an error middleware which is provided by the ExpressJS. ExpressJS Error Handling

For, 4 parameters middleware, the first arg is for error, Let's use the above example again

app.use((req, res, next) => {
  /* Do Some Stuff */
  /* Now, instead of changing values, we will pass an error to next function */
  next(new Error('Error Occured in this middleware!'))
  /* Now this error will reach 4 Args middleware, known as error middleware */
})


app.use((err, req, res, next) => {
  /* This middleware handles all errors that will be passed to next() function in any middleware */
  /* Let's console err here */
  console.log(err.message) // Error Occurred in this middleware!
})

Make sure to use error middleware to end of all middlewares.

Question 2:

If you want to set any header for res object you can use like this

app.use((req, res, next) => {
  /* Set Header to res object */
  res.set({
    'Content-Type': 'text/plain',
    'Content-Length': '123',
    'ETag': '12345'
  })

  /* and call next function, now this res object will pass to all middlewares after it.*/
  next()
})

Make sure to use this middleware above all middlewares, so you can access it in any middleware, This will set it as global headers for all middlewares

There are multiple ways to set headers in ExpressJS. Follow this answer to know more.

I hope this will help you to understand Express Middlewares.

Neeraj Kumar
  • 386
  • 2
  • 9