Home > Back-end >  What is the signature of express middlewares using typescript?
What is the signature of express middlewares using typescript?

Time:10-22

I have been learning and working with typescript. I am just curious to find out the correct signatures of express middlewares. I have been defining middlewares as:

const middleware = async(req: Request, res: Response, next: NextFunction) => {
    // Middleware code here
    if(ok) 
        next() 

    // Or I do
    return next()  
}

Is this the correct way? What is considered the best practice? Also what is supposed to be the return type of middlewares?

CodePudding user response:

Let's understand first what is middleware then will create a middleware. In express, middleware is a piece of code which will execute on every request. Middleware executes in same order of registration.

Let's create and register a middleware which will validate request's header token:

const app = express();

app.use((req: Request, resp, Response, next: NextFunction) => {
  // assume we created a validateToken token function somewhere
  const isValidToken  = validateToken(req);
  if (isValidToken) {
    // now we will use next function to pass this request to next middleware/route
    next();
  } else {
    // token is not valid so send back 401 response
    res.status(401);
    // as here we didn't called next function so response will return this middleware
  } 
});

So we seen middleware is just a callback function and express don't expect you to return anything from function. It provides next function to pass request to next middleware when you done with your task in middleware or send response t client right from your middleware. I hope it will clear your concept on middleware.

CodePudding user response:

Express middleware is of RequestHandler type. Here is a sample function that returns a typical middleware that tests for the authorization header.

export function requireAuthorization(): RequestHandler {
  return (req: Request, res: Response, next: Function) => {

    if (req.headers['authorization']) {
      res.status(403).send('Authorization header is required);
      return;
    }

    next();
  };
}
  • Related