Additional Features

Photo by FLY:D on Unsplash

Additional Features

#6 Article on the series

Introduction.

Hello there and welcome back. Thanks for reading to this point in the series. In case you missed where it all started, check here.

In this article, I will be discussing some features I didn't add to the project the first time I built it. So join me on this one.

User Input Validation.

This implementation is to sure that the data received from the user is in the proper format. I used a validation package called JOI. With JOI, the developer can describe how the data schema should look and the validation rules. You can install JOI with this command: npm install joi

/validators/user.Validator.js

const Joi = require("joi");
const validateUserMiddelWare = async (req, res, next) => {
  const userPayload = req.body;
  try {
    await userValidator.validateAsync(userPayload);
    next();
  } catch (error) {
    return res.status(406).send(error.details[0].message);
  }
};

const userValidator = Joi.object({
  email: Joi.string()
    .email({
      minDomainSegments: 2,
      tlds: { allow: ["com", "net"] },
    })
    .required(),
  password: Joi.string().pattern(new RegExp("^[a-zA-Z0-9]{3,30}$")),
  first_name: Joi.string().required(),
  last_name: Joi.string().required(),
});

module.exports = validateUserMiddelWare;

First, we require joi and define a middleware that will validate the user input. Next is to define the schema and set constraints.

/routes/authRoute.js

const userValidation = require("../validators/user.Validator");
userRouter.post(
  "/signup",
  userValidation,
  passport.authenticate("signup", { session: false }),
  authController.signUp
);

We added this route to our code earlier before. The only difference now is the userValidation middleware.

Rate Limiting.

Rate limiting is a feature that is being used to protect APIs from malicious attacks and to handle too many requests to APIs.

/app.js

const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
  windowMs: 20 * 60 * 1000, // 20 minutes
  max: 50,
  standardHeaders: true,
  legacyHeaders: false,
});
app.use(limiter);

First, install the express-rate-limit package from npm. Then configure the rateLimit object. This way it applies to all objects.

Security.

Security is very important in backend applications, especially when moving the application to a production environment. Here we will use helmet package. Install it and use it as middleware. It helps protect the application from web vulnerabilities.

/app.js

const helmet = require("helmet");
app.use(helmet);

Conclusion.

In this article, we discussed how to validate user input, limit the requests to our application and secure our application from web vulnerabilities. I hope you enjoyed this one.

Thanks for reading to the end.