How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
The Post/Redirect/Get (PRG) pattern is the go-to approach. After processing form data, a 302 redirection is implemented to a confirmation page or back to the initial form.
For example, in PHP:
With this, a refresh triggers a GET request to confirmation.php
, preventing repeat submissions.
Safeguarding user input data
It's critical to prevent resubmission, but also important to ensure the user doesn't lose their entered data. We can utilize sessions or cookies to hold the user's form data temporarily; this allows us to repopulate the forms upon redirection, ensuring a seamless user experience:
In JavaScript, localStorage
or sessionStorage
offer similar options without server-side manipulation.
Unique identifiers & server-side idempotence
Creating a unique identifier on form submission, either through user sessions or database entries, ensures each form submission is coupled with a unique token. We can validate this token on form submission and invalidate it afterwards to prevent re-entry:
In your form handling logic:
Client-side fortifications
Beyond server-side PRG, JavaScript client-side enhancements can also be put to use. The window.history.replaceState
is a key tool for manipulating browser history:
This technique removes form data from the browser's refresh action, redirecting to the same page sans the data, thus preventing resubmission.
Security practices
Maintain data integrity and protect your forms against Cross-Site Request Forgery (CSRF). Employ tokens and hashing algorithms to generate secure tokens. Validation checks during form processing further ensure safety.
Solver of the user experience puzzle
All applied techniques should be seamless, causing no user inconvenience. Validate inputs on the client-side first to prevent unnecessary server-side processing and potential resubmission pitfalls.
Test before you rest
Review your form submission processes regularly and conduct penetration tests. The server logic and client-side validation should work together to reliably prevent form resubmission.
Was this article helpful?