Henok Hailemariam
2 min readJul 4, 2020

--

NodeJS automated type validation for API requests

If you are building an API, it’s more likely that you will have to validate user data at some point and it’s often not a nice experience if you have to repeat the same validation logic multiple times. When I first started using Node with Express, I was validating data manually for each route and it was tedious so I started using a popular library, express-validator and it allowed me to automate that process. The following is a simplest usage of the library.

The above code solves the problem but I still wanted to simplify the validation process even more so I started looking for other alternatives.

One thing I like about statically typed languages such as Java or C++ is their support for types and it would be much simpler to validate data if we had something similar in JavaScript. TypeScript brings types to JavaScript but it’s more of a tool to simplify development than actually enforcing types since it doesn’t have runtime type checking so borrowing the type feature from Typescript, I wrote a little library that validates incoming requests on the fly.

Jebena is lightweight JSON validator and can be used with Express as below

npm i install jebena

It allows you to define your specs/rules in a similar fashion with how you define it with Typescript minus the interface syntax and it silently returns any errors to the client. It supports JavaScript primitive data types plus additional functions for advanced usage.

It validates any data against a JSON spec and can be used without Express. Below are some examples.

I hope this simple library helps you simplify your validation process.

--

--