412 Precondition Failed
One or more preconditions in the request header fields evaluated to false.
Usually happens because:
- ☑ Client requests modifications carrying If-Match
- ☑ Client requests If-Unmodified-Since dates older
🔍 Quick Checklist:
Meaning
The HTTP 412 Precondition Failed client error status code indicates that one or more preconditions given in the request header fields evaluated to false when tested on the server. This is used with conditional requests (e.g. If-Match, If-None-Match).
Root Causes
- Client requests modifications carrying If-Match headers that do not match the current server ETag hash.
- Client requests If-Unmodified-Since dates older than server modification states.
| Cause | Frequency |
|---|---|
| Client requests modifications carrying If-Match | ⭐⭐⭐⭐⭐ |
| Client requests If-Unmodified-Since dates older | ⭐⭐⭐⭐ |
Common Mistakes
- Using 412 instead of 304 (use 304 Not Modified for GET requests; use 412 Precondition Failed for write methods like PUT/POST/DELETE).
- Failing to update client ETag listings after success updates.
How to Fix
Framework-Specific Examples
Express middleware checking If-Match headers.
app.put('/api/data', (req, res) => {
const currentEtag = 'hash-123';
if (req.headers['if-match'] && req.headers['if-match'] !== currentEtag) {
return res.status(412).send('Precondition Failed');
}
});Server Configuration Examples
Nginx proxy configuration handling conditional requests.
# Nginx forwards conditional headers downstreamPrevention
- Ensure web API clients check ETag codes before executing updates.
Frequently Asked Questions (FAQ)
Q: What is the main purpose of 412 Precondition Failed?
It prevents the 'lost update' problem, where a client downloads a resource, edits it, and uploads it back, unknowingly overwriting changes made by another client in the meantime.
Q: How does 412 differ from 304?
Use 304 Not Modified for GET requests to verify caching. Use 412 Precondition Failed for state-changing requests (PUT, POST, DELETE) to verify concurrency locks.
Q: Which headers trigger 412 errors?
The main headers are 'If-Match', 'If-None-Match', 'If-Modified-Since', and 'If-Unmodified-Since'.
Q: How do clients recover from a 412 error?
The client must fetch the latest version of the resource to get the updated ETag, merge the changes, and try the PUT request again.