demarches-normaliennes/app/javascript/shared/ujs-error-handling.js
Pierre de La Morinerie 8dce7d59ed js: redirect to sign-in when a ujs link_to receives a 401
Before, when a 401 was received by a ujs-enabled link (like `link_to …,
method: :delete, data: { remote: true }`, rails-ujs tried to insert the
response text as a Javascript script.

As the script was something like `Please sign-in`, which is not valid
Javascript, the browser would throw an "Unexpected token" error.

The typical use-case is:

1. The user open a form in a tab,
2. The user disconnects in another tab,
3. In the first tab, the user clicks on a remote "Delete" link_to

In that case the browser raised an error in the console (and in Sentry),
but the user would see nothing.

With this commit, all 401 ujs errors are turned into redirects to the
sign-in page.

Fix https://sentry.io/organizations/demarches-simplifiees/issues/2522512693/activity/
2021-09-07 16:45:52 -05:00

8 lines
367 B
JavaScript

// For links and requests done through rails-ujs (mostly data-remote links),
// redirect to the sign-in page when the server responds '401 Unauthorized'.
document.body.addEventListener('ajax:error', (event) => {
const [, , xhr] = event.detail;
if (xhr && xhr.status == 401) {
location.reload(); // reload whole page so Devise will redirect to sign-in
}
});