Back to writing

Returning Useful Errors for Invalid JSON in a Node.js API

Tell callers what to fix when JSON is broken, too large, or missing a field. A small Node.js server with no extra packages.

Node.jsHTTPJSONBackendAPI Architecture

Your API receives broken JSON. The caller needs a useful error, not a blank response.

An API (application programming interface) lets two programs exchange data over a network. HTTP carries requests and responses between them. JSON is a text format for sending structured data as key-value pairs.

When you build an HTTP service in Node.js without a web framework, you need to read JSON yourself. Calling JSON.parse on incoming data can expose several problems. The caller might send plain text instead of JSON, send a body ten megabytes long, leave out a closing brace, or send an empty object when your code needs a person name.

If you do not handle these cases, your server can crash, leave the caller waiting, or return a confusing response.

Why raw Node.js needs explicit error handling

Frameworks like Express handle body reading through request helpers. With a raw http.createServer handler, Node.js gives you the request body as a readable stream.

Three details matter:

First, JSON.parse throws a SyntaxError when the JSON text is broken. It does not return null or an error object. In a native Node.js HTTP server, an unhandled error in an event callback can crash the server or leave the caller waiting until a timeout. node:http does not catch the error and turn it into an HTTP 500 response for you.

Second, streams deliver data in chunks. Without a size limit, large requests can use more memory than expected. If several callers send large bodies at once, keeping all their chunks at once can use too much memory.

Third, closing the connection too soon can stop the caller from receiving your response. If you call req.destroy() while the client is still sending data, the network connection closes abruptly. The client gets a connection error instead of your HTTP status code and message.

Four checks, then the success response

Run these four checks in order, then send a success response:

  1. Check the media type (HTTP 415): Make sure the Content-Type header says application/json. If someone sends XML or plain text, reject the request before reading its body.
  2. Limit the body size (HTTP 413): Count bytes as they arrive. If the request body is larger than your limit, such as 10 kilobytes, stop saving data and send an HTTP 413 Content Too Large response.
  3. Parse the JSON syntax (HTTP 400): Put JSON.parse inside a try/catch block. If parsing fails, send an HTTP 400 Bad Request response with a simple message. Do not send the raw JavaScript stack trace to the caller.
  4. Validate the fields (HTTP 422): Check that the parsed data is an object and that required fields are present and have the right types. If a required field is missing or a number is negative when it must be a positive integer, return HTTP 422 Unprocessable Content.
  5. Send the success response (HTTP 200): After the data passes all four checks, run your app code and return a clear JSON response.

RFC 9110 uses the renamed labels 413 Content Too Large and 422 Unprocessable Content, while some tools still print older names for the same numbers.

Checking the Content-Type header

Callers should say what kind of data they are sending. The Content-Type header tells you whether the request contains JSON.

Do not just check whether the header contains the word json. A client could send text/application/json-evil. Read the media type before any parameters, such as charset=utf-8. If the header is missing or the media type is not application/json, return HTTP 415 Unsupported Media Type.

Limiting memory without dropping the connection

To keep large request bodies from using too much memory, we count the bytes in each chunk. We also need to close the connection in a way that lets the caller receive the error.

If we destroy the request socket right away, the client may never receive the HTTP 413 response. Instead, we send the 413 response with a Connection: close header. We wait for the response finish event before closing the socket. While the response is being sent, we drain and discard any remaining chunks so we do not store them in memory.

If Content-Length is greater than the limit, the server sends 413 before reading any body chunk. It still counts bytes as chunks arrive because chunked requests have no Content-Length header.

Catching syntax errors safely

When JSON.parse fails, it throws a SyntaxError. Do not send the raw error message to the client. Node.js versions can format these messages differently, and stack traces can reveal internal file paths. Catch the error and return a short, fixed message that says the request body contains invalid JSON.

In this example, a request body that starts with a UTF-8 BOM returns HTTP 400 Bad Request.

Separating syntax errors from validation errors

Many APIs use HTTP 400 for every error. But broken JSON syntax and missing or invalid data are different problems:

  • Use HTTP 400 Bad Request when the text itself cannot be parsed as JSON.
  • Use HTTP 422 Unprocessable Content when the JSON parsed fine, but the data does not make sense for your application rules.

For example, { "name": "Apples", "quantity": -5 } is valid JSON, but the server cannot accept a negative quantity. Returning 422 tells the caller that the JSON was read, but a field value needs to be fixed.

We also use Number.isSafeInteger to check integer fields. In JavaScript, integers outside the safe range can lose precision, which can lead to unexpected values.

Complete runnable server

The complete server is in one file. Save it as server.mjs and run it with Node.js using node server.mjs:

Tested with Node.js v24.14.1.

The server matches the pathname, so a query string such as ?x=1 does not change the /api/records route.

node server.mjs

Here is the code:

import http from "node:http";
import { pathToFileURL } from "node:url";

export const MAX_BYTES = 10 * 1024; // 10 KB limit

export function isJsonContentType(header) {
  if (typeof header !== "string") return false;
  return header.split(";")[0].trim().toLowerCase() === "application/json";
}

export function sendJson(res, statusCode, data) {
  const payload = JSON.stringify(data);
  res.writeHead(statusCode, {
    "Content-Type": "application/json; charset=utf-8",
    "Content-Length": Buffer.byteLength(payload),
  });
  res.end(payload);
}

export function validateRecordSchema(data) {
  if (!data || typeof data !== "object" || Array.isArray(data)) {
    return "Payload must be a JSON object";
  }
  if (typeof data.name !== "string" || !data.name.trim()) {
    return "Field 'name' must be a non-empty string";
  }
  if (
    typeof data.quantity !== "number" ||
    !Number.isSafeInteger(data.quantity) ||
    data.quantity < 1
  ) {
    return "Field 'quantity' must be a positive integer";
  }
  return null;
}

export function createJsonServer() {
  return http.createServer((req, res) => {
    if (new URL(req.url, "http://localhost").pathname !== "/api/records") {
      return sendJson(res, 404, {
        error: "Not Found",
        message: "Endpoint not found",
      });
    }

    if (req.method !== "POST") {
      res.setHeader("Allow", "POST");
      return sendJson(res, 405, {
        error: "Method Not Allowed",
        message: "Only POST requests are supported",
      });
    }

    if (!isJsonContentType(req.headers["content-type"])) {
      return sendJson(res, 415, {
        error: "Unsupported Media Type",
        message: "Expected Content-Type: application/json",
      });
    }

    const declaredLen = parseInt(req.headers["content-length"] || "", 10);
    if (Number.isFinite(declaredLen) && declaredLen > MAX_BYTES) {
      res.writeHead(413, {
        "Content-Type": "application/json; charset=utf-8",
        Connection: "close",
      });
      res.end(
        JSON.stringify({
          error: "Content Too Large",
          message: `Payload exceeds limit of ${MAX_BYTES} bytes`,
        })
      );
      res.on("finish", () => req.destroy());
      req.resume();
      return;
    }

    let receivedBytes = 0;
    const chunks = [];
    let isOversized = false;

    req.on("data", (chunk) => {
      if (isOversized) return;
      receivedBytes += chunk.length;
      if (receivedBytes > MAX_BYTES) {
        isOversized = true;
        req.resume();
        res.writeHead(413, {
          "Content-Type": "application/json; charset=utf-8",
          Connection: "close",
        });
        res.end(
          JSON.stringify({
            error: "Content Too Large",
            message: `Payload exceeds limit of ${MAX_BYTES} bytes`,
          })
        );
        res.on("finish", () => req.destroy());
      } else {
        chunks.push(chunk);
      }
    });

    req.on("end", () => {
      if (isOversized) return;
      let parsed;
      try {
        parsed = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
      } catch {
        return sendJson(res, 400, {
          error: "Bad Request",
          message: "Malformed JSON payload",
        });
      }

      const schemaError = validateRecordSchema(parsed);
      if (schemaError) {
        return sendJson(res, 422, {
          error: "Unprocessable Content",
          message: schemaError,
        });
      }

      return sendJson(res, 200, {
        success: true,
        data: { name: parsed.name.trim(), quantity: parsed.quantity },
      });
    });

    req.on("error", () => {
      if (!res.headersSent) {
        sendJson(res, 500, {
          error: "Internal Server Error",
          message: "Socket error occurred",
        });
      }
    });
  });
}

if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  const server = createJsonServer();
  server.listen(3001, () => {
    console.log("Server listening on http://localhost:3001");
  });
}

How to test each response

Use these five curl requests to see the five responses:

First, send a request with no Content-Type header. The -H 'Content-Type:' option stops curl from adding a default header:

curl -i -X POST http://localhost:3001/api/records \
  -H 'Content-Type:' \
  -d '{"name":"item"}'

The server rejects the request and says it expects application/json.

Second, send a request body larger than 10 kilobytes. This command creates a temporary file with Node, sends it with curl, and removes the file:

node --input-type=module -e 'import fs from "node:fs"; fs.writeFileSync("large.json", JSON.stringify({ name: "large", quantity: 1, padding: "x".repeat(11000) }))'
curl -i -X POST http://localhost:3001/api/records \
  -H "Content-Type: application/json" \
  -d @large.json
rm -f large.json

The server stops saving new chunks and returns HTTP 413 Content Too Large.

Third, send broken JSON:

curl -i -X POST http://localhost:3001/api/records \
  -H "Content-Type: application/json" \
  -d '{"name": "missing quote}'

The server catches the parse error and returns HTTP 400 Bad Request.

Fourth, send valid JSON with an invalid field value:

curl -i -X POST http://localhost:3001/api/records \
  -H "Content-Type: application/json" \
  -d '{"name": "Widget", "quantity": -3}'

The server returns HTTP 422 Unprocessable Content because the quantity must be a positive integer.

Finally, send a valid record:

curl -i -X POST http://localhost:3001/api/records \
  -H "Content-Type: application/json" \
  -d '{"name": "Widget", "quantity": 10}'

The server returns HTTP 200 with the checked data. This example does not save the data, write to a database, or keep state.

This extra request confirms that a query string still reaches the handler. It is separate from the five response examples above.

curl -i -X POST 'http://localhost:3001/api/records?x=1' \
  -H "Content-Type: application/json" \
  -d '{"name": "Widget", "quantity": 10}'