DEV Community

OlumideSamuel
OlumideSamuel

Posted on

Implementing AutoLogout Feature in Web Applications (React-JS)

You might have noticed that certain applications logs you out automatically after a certain time of inactivity. This feature is particularly important when dealing with sensitive web applications like financial apps.

In this article, I would be showing you how to implement auto logout feature in a web application with Javascript in React-JS.

Prerequisite

We need a basic application with an auth feature implemented.
We would be building on this basic application I wrote earlier on Implementing Protected Route and Authentication in React-JS. You can clone from here Github.

It is a basic application with two pages that demonstrate user authentication.

  1. Login Page
  2. Home Page
    • On the home page, there is a logout button.

Login Credentials

Username: admin
Password: 123456

Implementation

We want to make sure the application logs user out automatically after 10 seconds of inactivity.

Basics

To start, we create an AppLogout component which will wrap the authenticated components and in which we shall implement the logout feature.

const AppLogout = ({ children }) => {
  return children;
};
export default AppLogout;
Enter fullscreen mode Exit fullscreen mode

NOTE: This can be done in the entry file of our main layout. But it's okay to create a separate component for separation of concerns.

In MainDashboardEntry (this should be the base entry file for all authenticated routes),

const MainDashboardEntry = () => {
    return (
        <AppLogout>
            <Home />
        </AppLogout>
    )
}
export default MainDashboardEntry
Enter fullscreen mode Exit fullscreen mode

In App.js,

function App() {
  return (
    <BrowserRouter>
      <Route exact path="/signin" component={Signin} />
      <ProtectedRoute exact path="/" component={MainDashboardEntry} />
    </BrowserRouter>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Now that the basics are covered, let's dive deep into AppLogout.js component.

A quick walkthrough of the solution is

  • List in an array events that determines user activity.
  • When component mounts, add listeners to the window that listens to the events.
  • Create a function that logs out user after 10 secs using setTimeout.
  • Each time any of the event is triggered, i.e mousemove, click, scroll, keypress etc, the timer to logout user after 10 secs of inactivity resets.
  • However, if none of the event is triggered within 10 secs, that is app is inactive, the app automatically logs out.

Below are some of the user events to guarantee user activity on the application

const events = [
  "load",
  "mousemove",
  "mousedown",
  "click",
  "scroll",
  "keypress",
];
Enter fullscreen mode Exit fullscreen mode

So, on successful login,

const events = [
  "load",
  "mousemove",
  "mousedown",
  "click",
  "scroll",
  "keypress",
];

const AppLogout = ({ children }) => {
  let timer;

// this function sets the timer that logs out the user after 10 secs
const handleLogoutTimer = () => {
  timer = setTimeout(() => {
    // clears any pending timer.
    resetTimer();
    // Listener clean up. Removes the existing event listener from the window
    Object.values(events).forEach((item) => {
      window.removeEventListener(item, resetTimer);
    });
    // logs out user
    logoutAction();
  }, 10000); // 10000ms = 10secs. You can change the time.
};

// this resets the timer if it exists.
const resetTimer = () => {
  if (timer) clearTimeout(timer);
};

// when component mounts, it adds an event listeners to the window
// each time any of the event is triggered, i.e on mouse move, click, scroll, keypress etc, the timer to logout user after 10 secs of inactivity resets.
// However, if none of the event is triggered within 10 secs, that is app is inactive, the app automatically logs out.
useEffect(() => {
  Object.values(events).forEach((item) => {
    window.addEventListener(item, () => {
      resetTimer();
      handleLogoutTimer();
    });
  });
}, []);

// logs out user by clearing out auth token in localStorage and redirecting url to /signin page.
const logoutAction = () => {
  localStorage.clear();
  window.location.pathname = "/signin";
};

  return children;
};

export default AppLogout;
Enter fullscreen mode Exit fullscreen mode

To see the demo of the application, check autoLogout.netlify.com

Here's a link to the Github Repository.
You can clone the app and test on your local machine.

If you enjoy reading this, like, share and bookmark this post. πŸ’™

Top comments (1)

Collapse
 
avoajaugochukwu profile image
Ugochukwu Avoaja

Thank you for this article.