DOCUMENTATION
MIDDLEWARES
Parse Data
Configuration

Parse Data Configuration

The parseData middleware offers full control over how data is parsed, validated, and protected.
It can be configured globally via app.parseData() or per route via parseData(config).


Configuration Structure

parseData({
  body: {
    type: "application/json", // MIME type filter (string or RegExp)
    raw: false, // Store unparsed Buffer in req.rawBody
    inflate: true, // Enable gzip/deflate/br decompression
    limit: 10 * 1024 * 1024, // Max size (10MB default)
  },
  parse: {
    query: true, // Parse query parameters
    params: true, // Parse URL parameters
    json: true, // Parse JSON bodies
    urlencoded: true, // Parse x-www-form-urlencoded bodies
    formData: true, // Parse multipart/form-data bodies
  },
  security: {
    escapeSQL: true, // Enable SQL sanitization
    verify: (req, rawBuffer) => {
      /* Custom verification logic */
    },
  },
});

⚙️ Body Options

OptionTypeDefaultDescription
typestring or RegExpundefinedRestricts parsing to specific MIME types (e.g. "application/json", /^text\//).
rawbooleanfalseIf true, stores unparsed body buffer in req.rawBody.
inflatebooleantrueEnables decompression for gzip, deflate, or br-encoded requests.
limitnumber10 * 1024 * 1024Defines max request body size (default 10MB).

🧩 Parse Options

OptionTypeDefaultDescription
querybooleantrueEnables query string parsing.
paramsbooleantrueEnables URL parameter parsing.
jsonbooleantrueEnables parsing for application/json requests.
urlencodedbooleantrueEnables parsing for application/x-www-form-urlencoded.
formDatabooleantrueEnables parsing for multipart/form-data.

🔒 Security Options

OptionTypeDefaultDescription
escapeSQLbooleanfalseSanitizes user input to mitigate SQL injection.
verify(req, rawBuffer) => voidundefinedAllows pre-parsing verification (useful for HMAC/webhook validation).

Example — Per Route Configuration

router.post(
  "/secure-upload",
  parseData({
    body: {
      type: "multipart/form-data",
      limit: 5 * 1024 * 1024, // 5MB limit
      inflate: true,
    },
    security: {
      escapeSQL: true,
      verify: (req, raw) => {
        const signature = req.headers["x-signature"];
        if (!verifySignature(raw, signature))
          throw new Error("Invalid signature");
      },
    },
  }),
  (req, res) => {
    console.log(req.body, req.files);
    res.status(200).end();
  }
);

🧱 Global vs Route-Level Priority

LevelBehavior
Global (app.parseData())Applies defaults to all routes.
Route (parseData(config))Overrides global settings for the route.

Example:

app.parseData({ body: { inflate: true } });
 
router.post(
  "/raw",
  parseData({ body: { raw: true } }), // Overrides global inflate
  (req, res) => {
    console.log(req.rawBody.toString("utf-8"));
    res.status(200).end();
  }
);

🧪 Error Handling Summary

CodeMessageCause
400Invalid Request DataMalformed JSON or body
400Invalid Compressed DataDecompression failed
415Unsupported Content-EncodingCompression disabled
413Payload Too LargeRequest exceeds limit
400Invalid Request Verificationsecurity.verify failed

✅ Best Practices

  • Use route-level configuration for endpoints with custom verification or MIME restrictions.- Keep inflate: true for clients that send compressed data.- Always apply body.limit to prevent denial-of-service via large payloads.- Use security.verify only when raw body access is needed (e.g., webhooks).- Combine escapeSQL with parameterized queries for maximum protection.
Copyright © 2024 - 2025 MIT by Mario Elvio