Back to BlogsNode.js

Validate Node.js API Input Before Running Business Logic

Anuj Singh (Admin) 14 September 2026 11 views

JSON parsing converts a request body into JavaScript values; it does not establish that those values are valid for your endpoint. An order quantity could be negative, a string, a Boolean or missing. Validate the contract before a request reaches database writes or other business actions.

Set a narrow request contract

The sample endpoint accepts only an itemCode string and quantity integer between 1 and 20. It uses Express and runs locally. The response demonstrates successful validation, not a real purchase, inventory reservation or payment operation.

const express = require("express");
const app = express();
app.use(express.json({ limit: "16kb" }));

app.post("/validate-order", (req, res) => {
  const body = req.body;
  if (!body || Array.isArray(body) || typeof body !== "object") {
    return res.status(400).json({ error: "Expected an object" });
  }
  const allowed = ["itemCode", "quantity"];
  if (Object.keys(body).some(key => !allowed.includes(key))) {
    return res.status(400).json({ error: "Unknown field" });
  }
  if (typeof body.itemCode !== "string" ||
      !/^[A-Z0-9-]{1,30}$/.test(body.itemCode) ||
      !Number.isInteger(body.quantity) ||
      body.quantity < 1 || body.quantity > 20) {
    return res.status(400).json({ error: "Invalid itemCode or quantity" });
  }
  return res.json({ valid: true });
});
app.listen(3001, "127.0.0.1");

Validate before normalization becomes ambiguous

This contract intentionally accepts uppercase item codes and rejects numeric strings for quantity. You could choose to normalize case or coerce strings, but that should be a documented behavior. Avoid spreading arbitrary request bodies into database models; select the fields the operation actually permits.

Separate syntax, validation and authorization

Malformed JSON is rejected by the body parser before the route runs. The endpoint should expose a consistent error format through appropriate error middleware. Valid input still does not establish permission: authentication, authorization and resource ownership checks are separate requirements for an actual protected operation.

Test boundary values, not just a happy request

Check quantities 0, 1, 20 and 21, plus "2", null and true. Test an empty object, an array and an extra field. Confirm invalid input produces no side effect. For a database-backed operation, validation should be followed by constraints and transaction behavior appropriate to the data.

Practice and check your understanding

Add a local integration test that sends each boundary case to the endpoint and checks the status. Then add a notes field with a maximum length, explicitly selecting it rather than accepting every new key.

Continue learning

Explore the related Code Hacker course syllabus for structured learning. Then read JavaScript Fetch: Handle HTTP Errors and Invalid JSON to connect this exercise to the next skill.

Reference

Express API reference provides the underlying API or technical guidance. Check the documentation for the version you use; examples here are small learning exercises rather than complete production implementations.

Found an issue with this guide? Send a correction with the article URL and your example. About our learning material.

Topics in this article

  • nodejs
  • express
  • api validation
  • http

Want to Learn This Practically?

Subscribe to Code Hacker and get hands-on access to 40+ premium courses — Ethical Hacking, Kali Linux, Metasploit, Network Hacking, Bug Bounty & more!