Skip to content

sombriks/node-backend-validation

Repository files navigation

CI tests

Samples on how to validate user data in node

Why validate input

For some of you, the question might seems absurd, but it's a valid question for anyone without any background, so:

Why validate data received from user or external service? Because:

  • No useful system can rely on random input.
  • Core principle of communication is meaning.
  • Data should be adherent to the system domain.
  • The early we validate, early we handle problems.
  • No backend service should blindly trust data received.

Samples

We showcase a few Node.js projects passing through distinct approaches to validation given certain constraints.

All projects offer the same REST API with a few differences regarding the validation strategy being experimented:

HTTP verb      Resource path                      Query parameters

GET,POST       /addresses                         q: string
GET,PUT,DELETE /addresses/{id}
GET            /addresses/{id}/people
PUT,DELETE     /addresses/{id}/people/{person_id}
GET,POST       /people                            q: string
GET,PUT,DELETE /people/{id}
GET            /people/{id}/phones                q: string
PUT,DELETE     /people/{id}/phones/{phone_id}

See each project for response codes and payload details.

What if we let data hit the database freely? This sample answers this question.

This project is meant to present the struggle of explicit validation.

Here we use joi, a validation framework for node.

In this project we leap from javascript to typescript and make use of static type check to help input data validation and development as well, thanks to type hints.

Noteworthy

  • There is also a small benchmark project using k6, putting the API under stress test, so we can observe the consequences of each approach.
  • There is coverage for all projects, but for some unknown reason, some of them report wrong line numbers, shifted by one or two.
  • Typescript gymnastics is tiresome and project tooling is passing through transformation or i just got bad luck.