In e-commerce applications, network instability or accidental user double-clicks can cause duplicate order submissions (POST /api/orders). Creating duplicate orders results in overcharging customers and inventory inconsistencies.
Your task is to implement Idempotency Key support on the Express backend and double-submit prevention on the React frontend.
Context & Problem
Currently, every request to POST /api/orders creates a brand-new order record in the database regardless of whether it is a duplicate attempt. Additionally, the checkout form in the frontend does not disable the submit button during an active submission.
Requirements
1. Backend (server/orders.js)
-
Read the Idempotency-Key header from incoming requests to POST /api/orders.
-
If Idempotency-Key is missing, return HTTP 400 Bad Request with { error: "Idempotency-Key header is required" }.
-
If payload validation fails (e.g., missing items array or items is empty), return HTTP 400 Bad Request with { error: "Invalid order payload" }.
-
If an order with the given Idempotency-Key already exists:
-
Do not create a new order or deduct inventory again.
-
Return the previously created order with HTTP 200 OK and set the response header X-Cache-Hit: true.
-
If it is a new valid request:
-
Store the order mapped to the Idempotency-Key.
-
Return the newly created order with HTTP 201 Created and set the response header X-Cache-Hit: false.
2. Frontend (src/Checkout.jsx)
-
Prevent duplicate submissions from the UI while a checkout request is pending:
-
Disable the "Place Order" button during submission.
-
Prevent secondary submit events while an active request is in flight.
-
Generate a unique idempotency key per checkout attempt and send it via the Idempotency-Key header in the fetch request.
Files to Modify
-
server/orders.js
-
src/Checkout.jsx