413 request entity too large and turbo-rails

Can anyone tell me how turbo-rails is supposed to handle the response from a post request that tries to upload a file that is larger than the server will accept?

I have nginx as a reverse proxy in front of a Rails 7 app. nginx rejects multi-part form submissions if the the request body is larger than client_max_body_size by immediately returning a 413 response to the browser, so that Rails never sees the request. This is the desired behavior, as we do not want to allow users to upload arbitrarily large files.

In the past, TurboLinks did not intercept form submissions, so that the 413 response was handled by the browser (it was not pretty, but at least it was clear to the user what the problem was). Now, turbo-rails just redisplays the form again, so users have no idea what happened. They think the system “erased” the information they “posted”.

How is this scenario supposed to be handled now that turbo-rails has taken over post requests?

I take it there is no way to handle this scenario?

I suggest looking into the turbo events turbo:submit-end or turbo:before-fetch-response. Something like:

document.addEventListener('turbo:before-fetch-response', (event) => {
  if(event.detail.fetchResponse.status === 413) {
    console.log('Payload Too Large')
  }
});

Thank you! Let me experiment with that. I will report on the results when done.

That worked very well, thank you. I ended up doing something like this:

document.addEventListener('turbo:before-fetch-response', (event) => {
  if (event.detail.fetchResponse.statusCode === 413) {
    alert('The file you attempted to upload is too large.  Please upload a smaller file.');
    event.preventDefault();
  }
});