Turbo caches and displays form validation errors when going back

On form validation errors our controller sends 422 along with error messages embedded in the view. On success it redirects to the next page.
However if the user clicks a link to go back after a successful form submission they see the cached form validation errors on the valid fields. We’re not doing anything fancy or custom with Turbo, other than disabling it on a couple of pages where we haven’t sorted out a JS conflict.

Reproduction notes:

  1. submit form with bad data - receive 422 and see error messages
  2. correct bad data and submit again - redirect to next step
  3. click back link - user sees validation errors but valid data from previous page

Is there an easy fix to prevent the page from caching when it has validation error messages? Technically the caching is correct, but I expected it wouldn’t cache when a page arrived with a 422.

Turbo 1.0.0
Rails 6.1

Things I’m considering doing:
A. when sending 422 add <meta name="turbo-cache-control" content="no-cache"> as well to opt out.
B. addEventListener("turbo:before-cache", function() and then somehow cleanup the validation error messages.

Is there a better way?
Thanks in advance.

This happens because when going back turbo displays a preview of the page. For me, placing

<meta name="turbo-cache-control" content="no-preview">

in the form page made it work.

@rockwell Thanks for the reply! I can try that, but I had assumed it would still fetch the page and replace the preview after fetching. Maybe its not?

Curious how others handle form validation errors… I’d think that’s got to be pretty common.

When clicking the back button turbo performs a Restoration visit. According to the docs

If possible, Turbo Drive will render a copy of the page from cache without making a request.

Sorry i explained wrongly. When pressing the back button it will still use the cached version. You ought to use the before-cache event. But, i just tried doing the same thing

Except, when clicking the backlink i did not see the errors there. Is your turbo version the latest one?

My version is of turbo-rails is 1.0.0. There is a 1.0.1, but I’m not seeing any changes in there that seem relevant. Still worth a try I suppose.

Edit: upgrading our JS side is probably a good move - we’re on 7.0.1 and at time of writing there’s a 7.1.1