Skip to content

[Bug]: Unintentional consecutive form submissions #81

Open

Description

@mcaskill

What did you expect? 🧐

I integrated Swup's Forms plugin for a contact form. I added the plugin's attributes [data-swup-form] and [data-swup-inline-form]. The form uses a POST method and has no action attribute (submits to the current page). The form includes Google reCAPTCHA. After a couple of weeks of use in production, we noticed a number of duplicate submissions in our database. We theorized that there is a demographic of our visitors that are double-clicking the form's submit button.

When you multi-click the submit form, depending on the speed of the visitor's clicks, the response time from the server, and the speed of Swup to replace the form, the visitor will be met with one of two outcomes:

  • They will see a successful form submission response; or
  • They will see an failed/invalid form submission response.

Without a CAPTCHA or one-time nonce:

  1. The visitor will mostly see a successful form submission. Unbeknownst to the visitor, multiple copies have been processed and emailed.

With a CAPTCHA or one-time nonce:

  1. The first submission is processed successfully by the server.
  2. The second submission fails on the server because the CAPTCHA token, or nonce, has already been validated/consumed by the first submission.
  3. Swup, depending on how fast the server is, replaces the form with either:
  • The successful form submission response (yay); or
  • The failed/invalid form submission response:
    1. The visitor assumes they made a mistake, or something went wrong, and tries again (possibly multi-clicking again).
    2. Rinse and repeat until the visitor either gets a successful response or abandons (unbeknownst to them, some requests were successful).

I failed to find the correct approach in Swup's documentation, and failed to assimilate all of Swup's and its Forms plugin' logic.

I naively thought I could use ignoreVisit for Swup.shouldIgnoreVisit in SwupFormsPlugin.beforeFormSubmit to block subsequent form submissions:

ignoreVisit: (url, { el } = {}) => {
	if (el?.closest('[data-no-swup]')) {
		return true;
	}

	if (el instanceof HTMLFormElement) {
		if (el.dataset.swupFormSubmitted) {
			return true;
		}

		el.dataset.swupFormSubmitted = 'true';
		return false;
	}

	return false;
}

I expected the second form submit event to be intercepted by my custom ignoreVisit function.

What actually happened? 😵‍💫

Little did I know, SwupFormsPlugin.submitForm uses Swup.navigate which in turn uses Swup.shouldIgnoreVisit again. My custom ignoreVisit function thinks its dealing with a subsequent form submit event and tells Swup to ignore the visit and Swup calls window.location.assign which reloads the entire page instead of replacing the form (from the [data-swup-inline-form] attribute). All form submissions were being ignored.

Some how (probably exhaustion that day) I never noticed the form was reloading the entire page instead of displaying the success/invalid message. I would have sworn form submissions were being processed and I was seeing the expected responses. This was deployed to production (🤦‍♂️) and the we ended up losing a few days worth of submissions.

I spent the day digging through Swup's logic and further exploring the documentation and eventually stumbled upon the "Create a plugin" page where I discovered I'm supposed to replace the Forms plugin's default handler:

The correct solution, ultimately is the following:

swup.hooks.replace('form:submit', (visit, args, defaultHandler) => {
	if (!args.el || !args.event) {
		return defaultHandler(visit, args);
	}

	if (!args.el.dataset?.swupFormSubmitted) {
		args.el.dataset.swupFormSubmitted = 'true';
		return defaultHandler(visit, args);
	}

	args.event?.preventDefault();
});

I must have missed these sections of information during my initial attempt because of the page's title being "Create a plugin". The "Hooks" page makes a single reference to a "default handler" and no mention that it could be replaced.

Ultimately, its my fault, and this is not much of a bug, and could be better filed as an issue in the swup/docs repository.

I'm filing it in this plugin's repository in case someone else finds themselves in my shoes.

Maybe there's something that could be done for this plugin such as adding an option to prevent consecutive submits. At the very least, improve the documentation by mentioning default handler replacements in the Hooks page and/or including the snippet above in the Forms plugin's page.

Thank you for your time,

P.S., the Replit demo I assembled, the signup.php file will return HTTP 400 half the time to give a proper idea potential fail states for visitors.

Screen capture of a Replit demonstration of Swup Forms plugin where a double-click of the form's submit button produced two different responses from the server

Swup and plugin versions 📝

  • swup: 4.8.1
  • @swup/forms-plugin: 3.6.0

What browsers are you seeing the problem on? 🧭

No response

Relevant log output 🤓

URL to minimal reproduction 🔗

https://replit.com/@mcaskill/Swup-Demo-Inline-Forms?v=1

Checked all these? 📚

Activity

  1. hirasso commented on Mar 7, 2025

    @hirasso
    Member

    Thank you @mcaskill for this amazingly detailed description of the issue and path to a solution!

    Not advertising swup.hooks.replace more prominently in the docs actually was a conscious decision we made, as in our experience, having to resort to replacing a hook often points to an underlying issue that can be optimized in swup or one of it's plugins directly.

    To prevent double-submissions, maybe we can do something directly in @swup/forms-plugin. My first idea would be to add the inert attribute to the whole form[data-swup-form] as soon as it is being submitted. That way, repeated submissions via mouse or keyboard would be impossible before the form was rendered again (either through a full visit or through an inline replacement).

    What do you think?

  2. mcaskill commented on Mar 8, 2025

    @mcaskill
    Author

    […] having to resort to replacing a hook often points to an underlying issue that can be optimized in swup or one of it's plugins directly.

    Makes sense.

    In my initial message, I highlighted that SwupFormsPlugin.submitForm uses Swup.navigate. I forgot to ask if there was a reason it was not using Swup.performNavigation directly like Swup.handleLinkClick does. That would bypass the risk of calling window.location.assign (although event.preventDefault() has already been called by that point).

    I also tried using Visit.abort (internal, I know) on the second submit during a before hook of form:submit but that just crashed all visit attempts (not sure why).

    To prevent double-submissions, maybe we can do something directly in @swup/forms-plugin […]

    In regards to "disabling" consecutive submits, this should be an opt-in feature. There are probably legit scenarios for consecutive submits.

    The [inert] attribute removes the element from the accessibility tree, makes the element unfocusable (if an interactive element had focus, it is lost and the visitor risks being sent back to the top of the page), and by default has no visual indication of inertness.

    The [disabled] attribute remains present in the accessibility tree (AT expresses its state: disabled/dimmed/unavailable) but becomes unfocusable (if an interactive element had focus, it is lost).

    The [aria-disabled] attribute remains present in the accessibility tree (AT expresses its state: disabled/dimmed/unavailable) and remains focusable but by default has no visual indication of unavailability (and requires JS logic to check for that attribute to avoid reacting to interactions).

    I think a new option similar to ignoreVisit might be sufficient. Something like:

    ignoreSubmit: (FormInfo, DelegatedSubmitEvent) => boolean
    new SwupFormsPlugin({
    	ignoreSubmit: (formInfo, event) => {
    		if (!event.delegateTarget) {
    			return false;
    		}
    	
    		if (!event.delegateTarget.dataset?.swupFormSubmitted) {
    			event.delegateTarget.dataset.swupFormSubmitted = 'true';
    			return false;
    		}
    	
    		return true;
    	}
    });

    Beyond blocking consecutive submits, it could possibly used for some kind of just-in-time state manipulation, invalidation, or some visual change.

    Speaking of accessibility, I've only briefly tested the @swup/a11y-plugin in a different project without @swup/forms-plugin. I noticed the Accessibility plugin toggles [aria-busy] on the document element. Could be practical if it toggled that attribute on the <form> element instead when paired with the Forms plugin.

  3. hirasso commented on Mar 9, 2025

    @hirasso
    Member

    In regards to "disabling" consecutive submits, this should be an opt-in feature. There are probably legit scenarios for consecutive submits.

    I can't think of a concrete scenario where allowing double submissions from the same swup form would be desirable. In fact, I'd argue that the current behavior is a bug that should be fixed. Since form[data-swup-form] elements are always intended to be sent to the server and replaced upon submission—whether through a full-page visit or an inline replacement—it makes sense that the form should only be open for submission again after it has been reloaded. This ensures a clean, predictable user experience. @daun, what are your thoughts?


    Speaking of accessibility, I've only briefly tested the @swup/a11y-plugin in a different project without @swup/forms-plugin. I noticed the Accessibility plugin toggles [aria-busy] on the document element. Could be practical if it toggled that attribute on the <form> element instead when paired with the Forms plugin.

    That’s a great point! Would you mind opening a new issue in @swup/a11y-plugin so we can track this idea? Right now, [aria-busy] is always applied to documentElement, regardless of whether the visit is a standard swup navigation or triggered by @swup/fragment-plugin / @swup/forms-plugin. Having the attribute on the <form> element specifically when using the forms plugin (or, more generally, on the containers that swup is currently replacing) could indeed be more practical.

  4. daun commented on Mar 9, 2025

    @daun
    Member

    I forgot to ask if there was a reason it was not using Swup.performNavigation directly like Swup.handleLinkClick does. That would bypass the risk of calling window.location.assign (although event.preventDefault() has already been called by that point).

    @mcaskill I think there was a reason. We spent a lot of time on the logic for form submissions, so most things in there are deliberate, but it's been a while and it doesn't come to mind, unfortunately. That's a really great case for "needs more inline comments".

    I can't think of a concrete scenario where allowing double submissions from the same swup form would be desirable. In fact, I'd argue that the current behavior is a bug that should be fixed.

    @hirasso I wouldn't see this as a bug. Plain html forms also allow consecutive submissions. It's just that with swup (or any other frontend router) things become slightly more complex to figure out when they go wrong 😑 I've recently built a swup inline form for an interactive counter, where consecutive submits were very much desired. So opt-in sounds fine to me, same as for the query param clean-up. I'm okay to stray from default browser behavior as long as we make it configurable.

  5. mcaskill commented on Mar 9, 2025

    @mcaskill
    Author

    I can't think of a concrete scenario where allowing double submissions from the same swup form would be desirable. […]

    Within the context of how Swup operates, it certainly makes sense.

    The example of using an interactive counter is great example of such a scenario (as long as each count doesn't need to be verified and the response is always successful).

    Would you mind opening a new issue in @swup/a11y-plugin so we can track this idea?

    Done: swup/a11y-plugin#71

  6. daun commented on Mar 9, 2025

    @daun
    Member

    @mcaskill We probably need a better way of allowing users to prevent form submissions, correct? A feature for prevention of duplicate submissions would be nice for sure, but it won't solve the general root issue here of having a way to abort form visits.

  7. mcaskill commented on Mar 10, 2025

    @mcaskill
    Author

    What I'm proposing with ignoreSubmit seems generic and flexible enough for preventing form submissions?

    The callback I would use isn't meant to be the default value of that option.

    If a default value is wanted, it could be:

    ignoreSubmit: (formInfo, event) => !event.delegateTarget.checkValidity()

    Maybe it could support async to allow one to perform long operations (which would require calling the form's event.preventDefault() if ignoreSubmit returns a Promise?

  8. daun commented on Mar 10, 2025

    @daun
    Member

    I'd love having a way to actively abort from inside the form:submit hook to bundle all the logic. Something like:

    swup.hooks.on('form:submit', (visit, { el: form, prevent }) => {
      if (form.dataset.submitting) {
        prevent()
      }
      form.dataset.submitting = true
    })

    This would however introduce a new proprietary way of aborting things, which is rather confusing. The ideal solution would somehow make use of event.preventDefault(). Maybe something like a SwupSubmitEvent that wraps the original SubmitEvent, where the original browser submission event is already prevented, but the wrapping swup submission event can be prevented.

  9. daun commented on Mar 10, 2025

    @daun
    Member

    Looking at the source, I think that's actually possible with a simple enough change. We could check if the original event was prevented because it's not prevented at the point we trigger the form:submit hook. Which would allow the following — would this work for you @mcaskill?

    swup.hooks.before('form:submit', (visit, { el: form, event }) => {
      if (form.dataset.submitting) {
        event.preventDefault()
      }
      form.dataset.submitting = true
    })
  10. mcaskill commented on Mar 10, 2025

    @mcaskill
    Author

    Since the submit's Event object is already passed to the hook, might as well use that.

    User-land:

    swup.hooks.on('form:submit', (visit, { el, event }) => {
    	if (el.dataset?.submitting) {
    		event.preventDefault();
    	} else {
    		el.dataset.submitting = true;
    	}
    });

    Swup-land (I doubt this is sufficient, I'm unsure of when the default handler is called in relation to added hooks):

    /**
     * Trigger the form:submit hook.
     */
    swup.hooks.callSync('form:submit', visit, { el: form, event }, () => {
    	if (!event.defaultPrevented) {
    		this.submitForm(event);
    	}
    });
  11. daun commented on Mar 10, 2025

    @daun
    Member

    From a cursory look, that should actually be enough!

  12. mcaskill commented on Mar 10, 2025

    @mcaskill
    Author

    I did not see your second reply when I posted mine 😄

    Indeed, Hooks.before would be the better call. Like you said, either the default handler of form:submit or FormsPlugin.submitForm just need to check if the event's default was already prevented.

  13. hirasso commented on Mar 11, 2025

    @hirasso
    Member

    For what its worth – I was curious if the browser would actually send double-submissions twice, so I built a little test page. Turns out, double submissions are absolutely possible, even without any JS involved. That was news to me, thanks for pointing it out @mcaskill . Here's the test page:

    https://test.rassohilber.com/double-submissions.php

    The form handler on my test page sleeps for 1 second before processing the form – that makes it easy to "double-click" before the response comes in. Here's the source code:

    <?php
    session_start();
    
    // Initialize session array if not set
    if (!isset($_SESSION['submissions'])) {
        $_SESSION['submissions'] = [];
    }
    
    // Simulate slow response
    sleep(1);
    
    // Add current timestamp to session log if this is a submission
    if (isset($_POST['is_submission'])) {
        $_SESSION['submissions'][] = date('Y-m-d H:i:s');
    }
    
    // Clear the submissions upon request
    if (isset($_POST['clear_submissions'])) {
        $_SESSION['submissions'] = [];
    }
    
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Double Submit Test</title>
        <style>
            :root {
                font-family: system-ui;
            }
            .forms {
                display: flex;
                gap: 0.5rem;
            }
        </style>
    </head>
    <body>
        <h1>Test Double Form Submission</h1>
    
        <div class="forms">
            <form method="POST">
                <input type="hidden" name="is_submission"></input>
                <button type="submit">Submit</button>
            </form>
    
            <?php if (!empty($_SESSION['submissions'])): ?>
                <form method="POST">
                    <input type="hidden" name="clear_submissions"></input>
                    <button type="submit">Clear</button>
                </form>
            <?php endif; ?>
        </div>
    
        <?php if (!empty($_SESSION['submissions'])): ?>
            <h2>Your Submissions:</h2>
            <ul>
                <?php foreach ($_SESSION['submissions'] as $submission): ?>
                    <li><?= htmlspecialchars($submission) ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    
        <p>Double-click "Submit" to test double submissions. Close and reopen the browser to reset the session.</p>
    </body>
    </html>

    Good to know that handling duplicate submissions always needs to be done on the server, regardless of how the form was submitted (via JS or not).

  14. mcaskill commented on Mar 11, 2025

    @mcaskill
    Author

    Thanks for the demo.

    I tested it in:

    • Chrome 134.0.6998.45
    • Firefox 137.0b4
    • Safari 18.3 (20620.2.4.11.5)

    In Chrome and Safari, I am able to send duplicate submits by multi-clicking the submit button.

    To my surprise, Firefox ignores the multi-clicks and sends only the first submit.

    Screen capture of three adjacent browsers, with their network inspector panels open, on the same Web page titled "Test Double Form Submission". From left to right: Chrome processed two submissions, Firefox processed one submission, and Safari processed two submissions.

  15. daun commented on Mar 12, 2025

    @daun
    Member

    We've started work on this in #84 in case you want to follow along! Otherwise, we'll keep this thread updated once it lands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions