HTTP 400 Error: Bad Request

Understanding and resolving malformed request errors.

The HTTP 400 "Bad Request" error is one of the most common client errors on the web. It indicates the server could not understand or process the request due to incorrect syntax, malformed data, or invalid parameters.

Unlike 5xx errors that signal a server problem, the 400 code points to a client-side issue. This could be a poorly encoded URL, an invalid JSON body, incorrect HTTP headers, or corrupted cookies. Identifying the exact cause requires methodical analysis.

For REST APIs and modern web applications, monitoring 400 errors is essential. A sudden spike in 400s can indicate a bug in your frontend, an incompatibility after an update, or an attack attempting to crash your system.

Main causes of 400 errors

400 errors can come from many sources. Here are the most common causes:

  • Malformed URL: Unencoded special characters, spaces in the URL, or invalid query parameters. Example: /page?name=John Doe instead of /page?name=John%20Doe.
  • Invalid request body: Malformed JSON, invalid XML, or form-data with incorrect structure. Missing braces or trailing commas are common mistakes.
  • Corrupted cookies: Cookies that are too large or contain invalid characters can cause a 400. This often happens after updates that change cookie format.
  • Invalid HTTP headers: Missing or incorrect Content-Type, malformed Authorization, or custom headers with forbidden values.

Diagnosing a 400 error

To identify the exact cause of a 400 error, follow this methodology:

  • Inspect the request: Use browser DevTools (Network tab) to examine the complete request: URL, headers, body, and cookies sent.
  • Test in isolation: Reproduce the request with curl or Postman to eliminate browser-related or cache variables.
  • Check server logs: Server logs often contain a detailed message explaining why the request was rejected.
  • Test in private mode: If the error disappears in private browsing, the problem likely comes from cookies or local cache.

Resolving 400 errors

Based on the identified cause, here are the solutions to apply:

  • Encode URL correctly: Use encodeURIComponent() in JavaScript or urlencode() in PHP for parameters containing special characters.
  • Validate JSON: Before sending a request, validate JSON with JSON.parse() or an online tool. Check for double quotes and absence of trailing commas.
  • Clear cookies: Delete cookies for the affected domain. If the problem is widespread, consider changing your cookie format.
  • Fix headers: Ensure Content-Type matches the body sent (application/json for JSON, multipart/form-data for files).

Validation and diagnostic examples

Here are code examples to diagnose and prevent 400 errors:

// JavaScript - Validate JSON before sending
function safeSendJSON(url, data) {
    try {
        const jsonString = JSON.stringify(data);
        JSON.parse(jsonString); // Validity check
        return fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: jsonString
        });
    } catch (e) {
        console.error("Invalid JSON:", e.message);
        throw new Error("Invalid data");
    }
}

// PHP - Server-side validation
$json = file_get_contents("php://input");
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON"]);
    exit;
}

Both client AND server-side validation is essential. Client-side for better UX, server-side for security.

Preventing 400 errors

Prevention is better than cure. Here are best practices:

  • Frontend validation: Validate form data before sending with libraries like Yup, Joi, or Zod.
  • Automated testing: Include integration tests that verify your API's behavior against invalid inputs.
  • Size limits: Document and validate request size limits (body, URL, cookies) to avoid overflows.
  • Clear error messages: Return descriptive error messages to help with debugging. Avoid generic 400s without explanation.

400 resolution checklist

  • URL properly encoded (no bare special characters)
  • Valid and well-formed JSON/XML request body
  • Non-corrupted cookies (test in private browsing)
  • Content-Type header matches body sent
  • Request size within server limits
  • Server logs checked for detailed error message

Frequently asked questions about HTTP 400

Is 400 a server or client error?

It's a client error (4xx codes). The server is working correctly but cannot process the request because it's malformed. It's up to the client to fix their request.

How to monitor 400 errors on my API?

Configure a MoniTao monitor with a valid request expecting HTTP 200. If your endpoint returns 400, you'll be alerted immediately. For APIs, create monitors with the correct body format and authentication.

Why does my form suddenly return 400?

Likely causes: corrupted cookies (try private browsing), frontend/backend update with format incompatibility, or stricter validation added server-side.

How to return a 400 with a useful message?

Return a structured JSON: {"error": "description", "field": "field_name", "details": "explanatory message"}. This helps enormously with client-side debugging.

Does 400 affect SEO?

Not directly for public pages that should return 200. However, if your public URLs return 400 due to poorly handled parameters, those pages won't be indexed.

What's the difference between 400 Bad Request and 422 Unprocessable Entity?

400 indicates a syntactically incorrect request (malformed JSON). 422 indicates a well-formed but semantically invalid request (email in wrong format inside valid JSON).

Conclusion

The HTTP 400 Bad Request error signals something is wrong with the request sent to the server. Best practice is to validate data client-side before sending, and provide explicit error messages server-side for easier diagnosis.

With MoniTao, monitor your critical endpoints and get alerted as soon as a 400 error appears. Proactive monitoring helps detect integration issues, post-update incompatibilities, and exploitation attempts before they impact your users.

Ready to Sleep Soundly?

Start free, no credit card required.