NextGen js request: logout action and event

Classic knack had Knack.logout(); which let you easily log out a user, e.g. when they click a custom button. This was useful if you built your own nav bar or had other reasons to log the user out and wanted to make that happen via js.

It doesn’t seem there is any such js api to initiate a logout with NextGen, but there should be!

Also, it would be great to have an event that fires when a user is logged out successfully e.g. Knack.on(‘logout’ => { ….. some code …. }); so that you could either redirect the user to a custom page or run some other code (e.g. clear the cookie from Intercom or similar chat widget).

Hey @jake5, there’s no current way to log out via JS in Next-Gen, but we’re pushing for it!

Regarding an event listener for a user signing out, it was just announced in this week’s update email (subscribe here).

Here’s the code:

Knack.on('user:signout', ({ user, pathname }) => {
  console.log("User:", user);
  console.log("Last page:", pathname);
  window.location.href = '#home'
});
2 Likes

Thanks, Stephen! That’s a great step in the right direction :slight_smile:

If anyone is trying to manually trigger a logout in next gen in the meantime before a proper js method is available, this custom javascript will work. It appends a custom logout link to a rich text view or any view element of your choice, which will log the user out when clicked by deleting the saved refreshToken in local storage. This seems to be how knack handles active sessions in nextgen.

Be sure to scroll because this code sample is long enough it’s being truncated by the forums.

// Logout Button
Knack.on('view:render:view_###YourViewNumberHere###', ({ pageKey }) => {

  // create a custom link element to use as the log out link
  // this is optional if you want it
  var logoutButton = '<a class="kn-button cursor-pointer h-10 p-3 rounded-lg print:hidden" href="#" id="custom-logout-link">Log Out</a>';

  // use jquery to append this custom link to some view on the page
  $("#view_###YourViewNumberHere###").append(logoutButton);

  // when the custom link is pressed
  $("#custom-logout-link").on('click', function (event) {
    event.preventDefault();
    
    // look through all of the localStorage entries to find the one 
    // starting with refreshToken - this is the active session token 
    // in knack nextgen
    var potentialKeys = [];
    Object.entries(localStorage).forEach(([key, value]) => {
      if (key.startsWith("refreshToken")) {
        potentialKeys.push(key);
      }
    });

    // if we found a localStorage item whose key starts with refreshToken
    // we delete it which effectively logs the user out
    // then we redirect them to our homepage or anywhere we'd like after logout
    if (potentialKeys.length > 0) {
      potentialKeys.forEach((element) => {
        localStorage.removeItem(element);
      });
      window.location.href = 'https://YourHomePageHere.com/index.html';
    }

  });
});