The 400 Bad Request status code indicates that the server cannot process the request due to a client-side error. This usually happens when the request syntax is invalid, required parameters are missing, or data sent by the client is malformed.
In HTTP communication, a 400 Bad Request response is returned when the server detects an issue with the request itself. This error is not related to authentication or authorization, but rather to how the request is structured or what data it contains.
// Sending an invalid JSON body causing 400 Bad Request
fetch("/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: "{ name: 'John' }" // Error: Malformed JSON (no quotes on key)
});
The server returns HTTP/1.1 400 Bad Request because the JSON body is malformed. Proper JSON requires double quotes around keys and string values.
Test how a server validates input. The simulated server below expects a Username. If you send it empty or include special characters (like @ or #), it will reject the request.
// Express.js example returning 400 for invalid input
app.post("/login", (req, res) => {
const { username } = req.body;
// Validation: Check if empty or contains special chars
const isValid = /^[a-zA-Z0-9]+$/.test(username);
if (!username || !isValid) {
return res.status(400).json({ error: "Invalid username format" });
}
res.status(200).send("Login successful");
});
Content-Type headers