Skip to content
tezvyn:
Menu

Never Trust Client Input: API Validation

Source: express-validator.github.ioMediumHow cards are made

Think of API validation as a bouncer for your server, checking every incoming request's ID before it can access your application logic. Use it in any Express route that accepts user input to prevent bad data from hitting your database or causing errors.

Why it exists

Applications are vulnerable when they blindly trust data from clients. Malicious or malformed input can cause crashes, data corruption, or security breaches like SQL injection. API request validation exists to create a defensive perimeter, ensuring that only data conforming to expected rules gets processed by your application logic.

The mental model

Think of API request validation as a strict contract for your API. The server defines the exact format, type, and constraints for all incoming data. Any request that violates this contract is rejected at the door, like a bouncer checking an ID. This frees your core business logic from having to worry about malformed or malicious inputs, simplifying code and hardening security.

How it works

In Express.js, validation is typically implemented as middleware that runs before your main route handler. Libraries like express-validator provide a "validation chain" where you declare rules for specific fields. The middleware intercepts the request, checks fields in req.body, req.query, req.params, req.headers, and req.cookies against these rules. If validation fails, it attaches an error object to the request, allowing your code to send a 400 Bad Request response before any business logic is touched.

When to use it

Use it on every single API endpoint that accepts input from an external source. This is non-negotiable for production systems. It's especially critical for routes that create or update data, such as user registration, profile updates, or any form submission. It protects your database integrity and prevents a wide class of bugs and security vulnerabilities.

When not to use it

There's almost no case where you shouldn't validate external input. However, you might skip it for internal-only, system-to-system APIs where the calling service is fully trusted and under your control, though even this is risky. Over-validation can also be a problem; applying overly strict rules (e.g., a very restrictive regex for names) can lead to poor user experience by rejecting valid inputs.

One canonical example

The express-validator library is a standard choice in the Node.js ecosystem. It wraps the powerful validator.js library. You can define a chain of checks for an endpoint, like ensuring a 'password' field in the request body is at least 8 characters long and a 'username' field is alphanumeric. If the incoming request fails these checks, the middleware stops the request from proceeding and lets you return a structured error message to the client.

Interview question

What is the primary function of API validation in an Express.js application?

  • a.To ensure that only authenticated users can access specific API endpoints.
  • b.To optimize database queries by pre-processing request parameters.
  • c.To prevent malformed or malicious client input from reaching the application's core business logic.Correct
  • d.To convert incoming client data into a standardized format for internal processing.
Why?

The card states that API validation's purpose is to create a "defensive perimeter" and ensure "only data conforming to expected rules gets processed," preventing "malicious or malformed input" from reaching application logic. Option A describes authentication/authorization, which determines who can access, not the validity of the data they send.

Just read this? Test yourself on what you have been reading.

Read the original → express-validator.github.io

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on nodejs — each one lists the topics its interview covers.

See open roles