Here is a solution with a more modular approach to chain validations, creating a middleware with a validator library specifically designed for express: express-validator.
Example of expected header Authorization: Bearer c8f27fee2a579fa4c3fa580
Install express-validator
package:
npm install --save express-validator
OR yarn add express-validator
- Create a middleware (e.g. in path
src/middlewares/validators.js
)
import { header, validationResult } from "express-validator";
export const myRequestHeaders = [
header('authorization')
.exists({ checkFalsy: true })
.withMessage("Missing Authorization Header") // you can specify the message to show if a validation has failed
.bail() // not necessary, but it stops execution if previous validation failed
//you can chain different validation rules
.contains("Bearer")
.withMessage("Authorization Token is not Bearer")
];
export function validateRequest(req, res, next) {
const validationErrors = validationResult(req);
const errorMessages = [];
for (const e of validationErrors.array()) {
errorMessages.push(e.msg);
}
if (!validationErrors.isEmpty()) {
return res.status(403).json({ "errors": errorMessages });
}
next();
}
use validator middlewares in your endpoint.
IMPORTANT: you need use the middlewares before your actual route function. Also, you need to chain the middleware such that the validateRequest
function (which actually verifies the validity of your request) comes after the expected header validator, in this case myRequestHeader
. See below:
app.use('/api/v1/your-endpoint', myRequestHeaders, validateRequest, async (req, res) => {
// the validator middleware will have already thrown a 403 if the header was missing,
// so you can be 100% sure that the header is present with validations your created.
console.log("req.headers.authorization", req.headers.authorization);
// do whatever you want
const actualToken = getBearerTokenFromHeader(req.headers.authorization); // c8f27fee2a579fa4c3fa580
res.sendStatus(200);
})
// helper function to get token value
const getBearerTokenFromHeader = (authToken) => {
return authToken.split(" ")[1]
}
With this library you can check the presence and quality of headers, parameters, body data and so on.