Implementing AutoLogout Feature in Web Applications (React-JS)
Tags: react, beginners, javascript, vue
Published: 2022-04-03 06:06:25

---
title: Implementing AutoLogout Feature in Web Applications (React-JS)
published: true
description: 
tags: react, beginners, javascript, Vue
cover_image: ![AutoLogout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4a74abo03ajkgeldjfn.png)
---

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](https://dev.to/olumidesamuel_/implementing-protected-route-and-authentication-in-react-js-3cl4). You can clone from here [Github](https://github.com/LuminousIT/auth-protected-route).

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.

```javascript
const AppLogout = ({ children }) => {
  return children;
};
export default AppLogout;
```
_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),
```javascript
const MainDashboardEntry = () => {
    return (
        <AppLogout>
            <Home />
        </AppLogout>
    )
}
export default MainDashboardEntry
```

In App.js,
```javascript
function App() {
  return (
    <BrowserRouter>
      <Route exact path="/signin" component={Signin} />
      <ProtectedRoute exact path="/" component={MainDashboardEntry} />
    </BrowserRouter>
  );
}
export default App;
```

#### <AppLogout />
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

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

So, on successful login, 
```javascript
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;
```
To see the demo of the application, check [autoLogout.netlify.com](https://autologout.netlify.app)

Here's a link to the [Github Repository](https://github.com/LuminousIT/auth-protected-route/tree/auto-logout-feature). 
You can clone the app and test on your local machine.

If you enjoy reading this, like, share and bookmark this post. 💙