HTTP
400 - Bad Request
Seeing a 400 Bad Request means the server rejected your request because it's malformed—invalid JSON syntax, missing required fields, or parameters that violate validation rules. This client-side error (4xx) happens when the browser or API client sends data the server can't parse or validate. Most common in API calls where JSON payloads have syntax errors, but also appears when form submissions miss required fields or URLs contain invalid query parameters.
#Common Causes
- →Frontend: Malformed JSON in request body—unclosed brackets, trailing commas, or invalid syntax. Missing Content-Type: application/json header. Invalid URL encoding in query parameters.
- →Backend: Request validation middleware rejects data before it reaches your handler. Database constraints fail during insertion. Missing request body parser middleware (express.json(), body-parser).
- →Infrastructure: Nginx/Apache misconfiguration rejects large request bodies. Load balancer strips required headers. Reverse proxy timeout cuts request mid-stream.
✓Solutions
- 1Step 1: Diagnose - Open browser DevTools Network tab, find the 400 request, check the Request Payload/Headers tab for syntax errors. Look for red-highlighted JSON or missing Content-Type headers.
- 2Step 2: Diagnose - Check server logs (tail -f /var/log/nginx/error.log or your app logs) for specific validation errors. Most frameworks log the exact field that failed.
- 3Step 3: Fix - Validate data client-side before sending: use JSON.parse() to test JSON validity, check required fields, validate email formats and string lengths.
- 4Step 4: Fix - Server-side: Add request validation middleware (express-validator, joi, zod) to catch errors early and return clear 400 messages. Ensure body-parser is configured with appropriate size limits.
- 5Step 5: Fix - Infrastructure: Increase client_max_body_size in Nginx if uploading files. Check proxy_read_timeout and proxy_connect_timeout settings. Verify headers aren't being stripped by the reverse proxy.
</>Code Examples
Fetch API: Client-Side Validation
1// Validate request before sending to prevent 400 errors
2const validateRequest = (data) => {
3 if (!data.email || !data.email.includes('@')) {
4 throw new Error('Invalid email format');
5 }
6 if (!data.name || data.name.length < 2) {
7 throw new Error('Name must be at least 2 characters');
8 }
9 return true;
10};
11
12// Usage with proper error handling
13try {
14 validateRequest(requestData);
15 const response = await fetch('/api/endpoint', {
16 method: 'POST',
17 headers: { 'Content-Type': 'application/json' },
18 body: JSON.stringify(requestData),
19 });
20
21 if (!response.ok && response.status === 400) {
22 const error = await response.json();
23 console.error('Validation error:', error.message);
24 }
25} catch (error) {
26 console.error('Request error:', error.message);
27}Express.js: Request Validation Middleware
1// Server-side validation middleware to catch 400 errors early
2const express = require('express');
3const { body, validationResult } = require('express-validator');
4const app = express();
5
6app.use(express.json({ limit: '10mb' }));
7
8// Validation middleware
9const validateUser = [
10 body('email').isEmail().withMessage('Invalid email format'),
11 body('name').isLength({ min: 2 }).withMessage('Name must be at least 2 characters'),
12 (req, res, next) => {
13 const errors = validationResult(req);
14 if (!errors.isEmpty()) {
15 return res.status(400).json({ errors: errors.array() });
16 }
17 next();
18 }
19];
20
21// Apply validation to route
22app.post('/api/users', validateUser, (req, res) => {
23 // Request is validated, proceed with business logic
24 res.json({ success: true, user: req.body });
25});Nginx: Increase Request Body Size Limit
1# Nginx configuration to handle larger request bodies
2# In your server or location block:
3
4server {
5 listen 80;
6 server_name api.example.com;
7
8 # Increase client body size limit (default is 1MB)
9 client_max_body_size 10m;
10
11 # Increase buffer sizes for large headers
12 client_header_buffer_size 4k;
13 large_client_header_buffers 4 16k;
14
15 # Timeouts for slow clients
16 client_body_timeout 60s;
17 client_header_timeout 60s;
18
19 location /api/ {
20 proxy_pass http://backend;
21 proxy_set_header Host $host;
22 proxy_set_header X-Real-IP $remote_addr;
23 }
24}↗Related Errors
Provider Information
This error code is specific to HTTP services. For more information, refer to the official HTTP documentation.