On this page
Refreshing a page returned directly from a form submission can cause the browser to offer to resend the POST request. The post redirect get pattern (PRG) changes the successful flow: the server processes the POST, redirects the browser, and serves the result with a separate GET. Refreshing that result page then repeats the GET rather than the form POST.
Key Takeaways
- After a successful POST, return
303 See Otherwith aLocationpointing to a result page. - The browser follows the redirect with a GET; refreshing the result page repeats that GET.
- Validation errors can be returned directly from the POST so the user can correct the form.
- PRG does not prevent double-clicks, retries, or concurrent duplicate requests. Important operations still need server-side duplicate safeguards.
How the post redirect get pattern works
Without a redirect, a typical sequence is: the browser sends a POST, the server performs an action, and the server returns an HTML result in the POST response. Because that result is associated with the POST, refreshing it may prompt the browser to resubmit the form. If accepted, the server may perform the action again.
With PRG, the successful sequence is:
- The browser sends the form data in a POST request.
- The server validates the data and performs the action.
- The server responds with
303 See Otherand aLocationheader. - The browser requests that location with GET and displays the result.
- Refreshing the displayed result repeats the GET, not the original POST.
The action happens before the redirect. If the server fails before responding, the client may not know whether the action succeeded; PRG alone cannot resolve that uncertainty.
Advertisement
Choose the redirect status deliberately
For a successful form POST, 303 See Other explicitly directs the client to retrieve another resource, normally with GET. It communicates the intended POST-to-GET transition more clearly than a generic redirect.
| Status | Practical distinction after a POST |
|---|---|
303 See Other | Directs the client to retrieve the target, normally using GET. |
301 Moved Permanently or 302 Found | Some clients may change POST to GET for historical compatibility; do not depend on these statuses to express PRG unambiguously. |
307 Temporary Redirect or 308 Permanent Redirect | Preserve the request method when followed, so a POST remains a POST. These are not the usual choice for a PRG result page. |
These distinctions follow the HTTP semantics described by RFC 9110. The RFC was not retrieved for this article, so consult it directly when checking detailed client or protocol requirements.
Minimal example: a local form and receipt
This example uses Python's standard library. It accepts a name, creates an in-memory receipt, and redirects to a GET URL for that receipt. It binds to the local machine and is intended for learning, not deployment. The code was not executed for this article.
Save it as prg_demo.py:
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit
from uuid import uuid4
# Lost when the process stops; suitable only for this local demonstration.
receipts = {}
def form_page(message="", name=""):
return (
"<!doctype html><html><body>"
f"<p>{escape(message)}</p>"
'<form method="post" action="/submit">'
'<label>Name: '
f'<input name="name" value="{escape(name, quote=True)}">'
'</label> <button type="submit">Submit</button>'
'</form></body></html>'
)
class Handler(BaseHTTPRequestHandler):
def send_html(self, status, html):
body = html.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
path = urlsplit(self.path).path
if path == "/":
self.send_html(200, form_page())
elif path.startswith("/receipt/"):
receipt_id = path.removeprefix("/receipt/")
name = receipts.get(receipt_id)
if name is None:
self.send_error(404, "Receipt not found")
return
self.send_html(200, f"<h1>Receipt</h1><p>Saved: {escape(name)}</p>")
else:
self.send_error(404)
def do_POST(self):
if urlsplit(self.path).path != "/submit":
self.send_error(404)
return
try:
length = int(self.headers.get("Content-Length", ""))
except ValueError:
self.send_error(400, "Invalid Content-Length")
return
if length < 0 or length > 4096:
self.send_error(413, "Request too large")
return
try:
data = self.rfile.read(length).decode("utf-8")
except UnicodeDecodeError:
self.send_error(400, "Expected UTF-8 form data")
return
fields = parse_qs(data, keep_blank_values=True)
name = fields.get("name", [""])[0].strip()
if not name:
self.send_html(422, form_page("Enter a name.", name))
return
receipt_id = uuid4().hex
receipts[receipt_id] = name
self.send_response(303)
self.send_header("Location", f"/receipt/{receipt_id}")
self.send_header("Content-Length", "0")
self.end_headers()
if __name__ == "__main__":
server = HTTPServer(("127.0.0.1", 8000), Handler)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
Run it with Python 3.9 or later:
python3 prg_demo.py
Open http://127.0.0.1:8000/, enter a name, and submit. The expected result is a receipt URL containing a generated identifier. Refreshing that page requests the same receipt; it does not create another one. Stop the server with Ctrl+C. Receipts disappear when the process stops, so old receipt URLs then return 404.
The example escapes the submitted name before putting it into HTML. It does not provide authentication, CSRF protection, durable storage, or duplicate-submit protection; add appropriate controls before building a real application.
Verify the redirect and final URL
In your browser's developer tools, open the Network panel and enable Preserve log if available. Submit the local form and inspect the requests:
- Select
POST /submitand check for status303and aLocationresponse header. - Find the subsequent GET to the receipt path and check its response.
- Refresh the receipt page and confirm that the new request is a GET, not another POST.
You can also inspect the redirect without following it:
curl -i -d 'name=Ada' http://127.0.0.1:8000/submit
The response should contain a 303 status and a Location header. To inspect the redirect chain as well, run:
curl -i -L -d 'name=Ada' http://127.0.0.1:8000/submit
Look for the redirect response followed by the receipt response. Avoid adding -X POST to this command: explicitly forcing the method can change how curl follows the redirect and makes this PRG check misleading. Each command sends a separate POST and creates a separate receipt.
Advertisement
Validation errors and duplicate submissions
The example returns a 422 response with the form when the name is empty. No receipt is created, so there is no successful action to redirect after. Refreshing that error page may still prompt for resubmission; the user should correct the form and submit it again.
An alternative is to redirect back to the form after a validation failure and carry errors and permitted input in a short-lived server-side session. This avoids leaving a POST response as the displayed page, but requires session management and careful handling of sensitive input. Do not put passwords or other sensitive form values in a redirect URL.
PRG only changes navigation after a successful response. It does not stop two POSTs sent before the redirect, a client retry after a timeout, or requests from multiple tabs. For operations such as payment or order creation, use a server-side idempotency design:
- Give each intended operation an idempotency key and scope it to the authenticated user or account.
- Enforce uniqueness atomically in persistent storage, and store enough information to return the original result for a retry. Define what happens if the same key is reused with different input.
- Coordinate the deduplication record and the business change transactionally where possible. External side effects need their own retry and reconciliation strategy; a database transaction alone cannot guarantee an external service acted exactly once.
- Use business-specific constraints where appropriate, rather than treating every similar request as a duplicate.
Disabling the submit button after a click can improve the interface, but it is not a security or correctness boundary. The local example deliberately creates a new receipt for every valid POST, including duplicate requests.
Common Mistakes
- Returning a success page directly from POST: refreshing it can prompt a form resubmission.
- Using
307or308for the result redirect: the client preserves POST instead of switching to the intended GET. - Performing the action in the result GET: refreshes, links, or automated requests could repeat the side effect. Keep the GET read-only.
- Assuming PRG prevents duplicate actions: retries and near-simultaneous submissions can reach the server before any redirect is followed.
- Treating an identifier as authorization: a real receipt endpoint must enforce the application's access rules, even if its identifier is hard to guess.
Best Practices
- Redirect to a stable result URL that can retrieve the outcome after the POST completes. Handle missing or expired results explicitly.
- Validate and authorize on the server, protect state-changing requests against CSRF where applicable, and escape untrusted data in rendered HTML.
- Keep sensitive data out of URLs, which can appear in browser history and logs.
- Test the POST response, the redirected GET, validation failures, and duplicate or retried submissions separately.
Conclusion
Use 303 See Other after a successful form POST to make the displayed result a GET resource. Pair PRG with server-side validation and, where duplicate actions matter, durable idempotency safeguards.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.