← Back to Chapters

412 Precondition Failed

? 412 Precondition Failed

? Quick Overview

The 412 Precondition Failed HTTP status code indicates that one or more conditions specified in the request headers were not met by the server. This response is commonly associated with conditional requests using headers like If-Match, If-Unmodified-Since, or If-None-Match.

? Key Concepts

  • Used in conditional HTTP requests
  • Helps prevent accidental overwrites
  • Often used with ETags and caching
  • Returned before request body is processed

? Syntax / Theory

A client sends a request with a precondition header. If the condition evaluates to false, the server rejects the request with status code 412.

? Code Example(s)

? View Code Example
// Example of a conditional GET request using Fetch API
fetch("/api/resource", {
  headers: {
    "If-Match": "etag-value"
  }
})
.then(res => {
  if (res.status === 412) {
    console.log("Precondition failed");
  }
});

? Live Output / Explanation

Server Response

If the ETag sent in If-Match does not match the server’s current version, the server responds with 412 Precondition Failed and no data is modified.

? Interactive Example

Scenario: The server expects the specific ETag "v1" to allow updates.

 
? View Logic Code
// Simulated server-side condition check
const clientETag = "v1"; // The Simulated Server Version

function checkCondition(inputETag) {
  if (inputETag !== clientETag) {
    return "412 Precondition Failed"; 
  }
  return "200 OK - Update Success";
}

? Use Cases

  • REST APIs with optimistic locking
  • Preventing lost updates in concurrent systems
  • Cache validation using ETags
  • Safe PUT and DELETE operations

✅ Tips & Best Practices

  • Always generate and manage ETags correctly
  • Use conditional headers for write operations
  • Handle 412 responses gracefully on the client
  • Document preconditions clearly in APIs

? Try It Yourself

  • Create a REST API endpoint with ETag support
  • Send requests with incorrect If-Match values
  • Observe how the server responds with 412
  • Modify logic to return updated ETags