rhondamuse.com

Essential Data Validation Techniques for ExpressJS APIs

Written on

Chapter 1: Introduction to Data Validation

Ensuring the integrity of the data sent to your API is crucial for maintaining security.

Data security illustration

A common piece of advice I've encountered throughout my career is:

"Never trust the frontend."

This principle stems from the fact that we lack control over the data being submitted to our APIs, making it necessary to verify that the information received is accurate and secure.

In strongly typed languages such as Java, if the frontend transmits data that doesn't align with what the API expects, an error is typically thrown. However, JavaScript operates quite differently. Since objects in JavaScript are created at runtime, it's all too easy to send incorrect data, which can lead to serious issues, such as corrupting your database with invalid entries.

JavaScript lacks robust mechanisms for validating incoming objects, and this gap remains even with TypeScript. Fortunately, there are two libraries available that can simplify data validation in your Express API, allowing you to trust the data without needing to manually inspect each property of nested objects.

The libraries we will explore are:

  • Celebrate: A middleware function for Express that integrates with Joi for validation.
  • Joi: A powerful schema validation library.

Chapter 2: Overview of Celebrate and Joi

The reason for utilizing both libraries is that Celebrate acts as an ExpressJS wrapper around Joi, providing a convenient way to ensure that the objects being processed conform to the specified structure.

To illustrate, let's create an endpoint for validating the body of a POST request for creating a recipe:

app.post('/recipe/create', async (req, res, next) => {

res.send('OK');

});

We want to ensure that the data in the request body adheres to the following structure:

{

"name": "string",

"description": "string (optional)",

"ingredients": [{"name": "string"}],

"owner": {"id": "string"}

}

To implement this validation, we need to include the following imports:

import { celebrate } from 'celebrate';

import Joi from 'joi';

Next, we can set up our validation logic. If you're familiar with prop-types in React, the syntax should feel familiar:

app.post(

'/recipe/create',

celebrate({

body: {

name: Joi.string().required(),

description: Joi.string(),

ingredients: Joi.array().items({

name: Joi.string().required()

}).required(),

owner: Joi.object({

id: Joi.string().required()

}).required()

}

}),

async (req, res, next) => {

res.send('OK');

}

);

Notice how Celebrate functions as a handler, positioned between the URL and your actual endpoint handler. When defining an array of objects, you must use the items method and provide the structure for the objects contained within the array.

I suggest placing the validation directly after the URL, especially if you are modifying the request body on the fly. This approach helps prevent false positives that may arise from mismatched payloads.

Celebrate takes an object parameter where you specify the expected structure. You can define the body for JSON payloads (in POST requests) and query parameters as needed. Within your body definition, you can outline the structure using Joi's types, employing required() to enforce necessary fields. Remember to apply this requirement to both arrays and objects to avoid errors.

If you attempt to interact with the API using an invalid request body, you will receive an error, effectively safeguarding your application.

Chapter 3: Validating Query Parameters

Validating query parameters is equally straightforward! Simply replace body with query. The good news is that both validation methods can coexist, allowing you to define a body object and a query object simultaneously.

That's a wrap for today! I hope this guide proves valuable and enjoyable for you. Implementing these validation techniques has been a game changer for ensuring the robustness of my backend systems.

For more insights, check out PlainEnglish.io and subscribe to our free weekly newsletter. Stay connected with us on Twitter, LinkedIn, YouTube, and Discord.

This video provides a detailed walkthrough on data validation with ExpressJS.

In this video, learn more about validation techniques in ExpressJS.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Loose Change: Finding Inspiration in the Little Things

Discover how small moments and unexpected sparks can reignite your passion for writing, even when faced with challenges.

# Unraveling the Mystery of ‘Oumuamua: An Interstellar Enigma

Explore the theories surrounding 'Oumuamua, the enigmatic interstellar object, and its implications for understanding the cosmos.

Uncovering Hidden Barriers: The Counterproductive Nature of Common Coping Strategies

Explore the unexpected downsides of five coping strategies that can hinder true healing and well-being.

Exploring Elon Musk's Satirical Self-Improvement Podcast

Dive into Elon Musk's ironic affirmations podcast, examining contradictions in mindfulness, capitalism, and more with a humorous twist.

Title: Navigating Fatherhood Doubts: A Letter to Future Children

A heartfelt exploration of fatherhood doubts and personal growth, addressing the challenges of becoming a better man for future children.

A Comprehensive Reading List for 2023: 26 Must-Reads

Explore 26 essential books to read in 2023, offering insights into personal growth, knowledge, and entertainment.

The Impact of Netflix on Global Culture and Media Dynamics

Analyzing Netflix's role in media imperialism and its cultural effects in the global landscape.

From 100 Followers to Real Success: The Journey Begins

Celebrating the achievement of 100 followers and exploring the next steps in writing and earning.