liferay/senna.js

Add custom behavior when a Redirect happens (302)

lneves12 opened this issue · 4 comments

Expected behavior

To be possible to add custom behavior when a Redirect happens.

Actual behavior

I have a use case that whenever I press a link and it returns a "302" I want to redirect the full page and force a refresh instead of injecting the result in the surfaces, for instance, redirecting to a login page if the session is lost. The problem here is that the redirect is automatically done by the XMLHttpRequest https://github.com/metal/metal-plugins/blob/master/packages/metal-ajax/src/Ajax.js#L66, therefore, the path in the routes/lifecycle events will always be the original one with the return status code of 302, making it hard to add custom logic there

One possible solution:#302

  appInstance.on('endNavigate', function(navigation) {
    if(appInstance.browserPathBeforeNavigate.path.includes("login")) {
      window.location = appInstance.browserPathBeforeNavigate.path;
    }
  });

The problem of this solution is that using the event 'endNavigate' the surfaces will be already updated, which is not nice.

I was thinking of adding a new event like 'beforeReplacementNavigation'.

What do you think? Any suggestion?

I am willing to implement this, just want to reach an agreement with you first :)

I can always implement a workaround server side and if the Senna header is present inject some javascript to refresh the page, but I am not thrilled with that solution.

Current workaround:

  appInstance.on('endNavigate', function(navigation) {
    const urlPath = appInstance.browserPathBeforeNavigate;
    if(urlPath.includes("loginPath")) {
      document.getElementsById("id").innerHTML = `
        <div class="container-fluid">
            <div class="alert alert-danger">
                No session. Redirecting to login page...
            </div>
        </div>
      `;
      window.location = urlPath;
    }
  });

I think this will be easier to implement since we are now using the Fetch api instead of the XMLHttpRequest one

This workaround "browserPathBeforeNavigate" doesn't work anymore for version 3 of senna.js.

Implemented solution: on the backed if the Http header "x-pjax" is defined we return a 401 instead of 302. This way in the "endnavigation" handler we can just redirect to the login page :)

This issue doesn't make sense anymore