Enhancing React App Security: Implementing Inactivity Logout for Peace of Mind
Tags: security, react, reactjsdevelopment, frontend
Published: 2024-04-21 12:36:19

In many web applications, it's crucial to ensure security by automatically logging users out after a period of inactivity. This feature becomes especially important for sensitive applications like financial platforms. In this tutorial, we'll explore how to implement an inactivity logout feature in a React application using JavaScript


**Prerequisites:**

Before diving into the implementation, make sure you have a basic React application set up with user authentication. We'll build upon this existing setup to incorporate the inactivity logout feature.


**1. The Watchtower: InactivityLogoutTimer Component**

This is the heart of our security setup. The InactivityLogoutTimer component keeps an eye on things and logs users out if they've been inactive for too long.


```javascript
// Inside InactivityLogoutTimer.jsx
const InactivityLogoutTimer = () => {
    // Functions to check for inactivity and update expiry time...
};
```



 **2. Watching for Inactivity**

Here, we'll dive into how we check if a user has been idle for too long and needs to be logged out.

```javascript
 const checkForInactivity = () => {
        const expireTimeString = localStorage.getItem('expireTime');
        const expireTime = expireTimeString ? parseInt(expireTimeString) : 0;

        if (expireTime < Date.now() && location.pathname !== '/') {
            localStorage.removeItem('token');
            navigate('/');
        }
    };
```




**3. Keeping Time: Updating Expiry**

We'll make sure user sessions expire after a set period to keep things secure.

```javascript
    const updateExpiryTime = () => {
        const expireTime = Date.now() + 2 * 60 * 60 * 1000; // 2 hours in milliseconds
        localStorage.setItem('expireTime', expireTime.toString());
    };
```

**4. Standing Guard: Setting Event Listeners**

To keep an eye on user activity, we'll set up listeners for mouse movements, clicks, and other actions.

```javascript
useEffect(() => {
    updateExpiryTime();
    window.addEventListener('click', updateExpiryTime);
    window.addEventListener('keypress', updateExpiryTime);
    window.addEventListener('scroll', updateExpiryTime);
    window.addEventListener('mousemove', updateExpiryTime);

    return () => {
        window.removeEventListener('click', updateExpiryTime);
        window.removeEventListener('keypress', updateExpiryTime);
        window.removeEventListener('scroll', updateExpiryTime);
        window.removeEventListener('mousemove', updateExpiryTime);
    };
}, []);
```


**5. Putting It All Together**

Once we've got all our pieces in place, we'll integrate everything into our React app. This will make sure our users stay safe without any hassle.

```javascript
import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

const InactivityLogoutTimer = () => {
    const location = useLocation();
    const navigate = useNavigate();

    const checkForInactivity = () => {
        const expireTimeString = localStorage.getItem('expireTime');
        const expireTime = expireTimeString ? parseInt(expireTimeString) : 0;

        if (expireTime < Date.now() && location.pathname !== '/') {
            localStorage.removeItem('token');
            navigate('/');
        }
    };

    const updateExpiryTime = () => {
        const expireTime = Date.now() + 2 * 60 * 60 * 1000; // 2 hours in milliseconds
        localStorage.setItem('expireTime', expireTime.toString());
    };

    useEffect(() => {
        const interval = setInterval(() => {
            checkForInactivity();
        }, 5000); // Check for inactivity every 5 seconds

        return () => clearInterval(interval);
    }, []);

    useEffect(() => {
        updateExpiryTime();
        window.addEventListener('click', updateExpiryTime);
        window.addEventListener('keypress', updateExpiryTime);
        window.addEventListener('scroll', updateExpiryTime);
        window.addEventListener('mousemove', updateExpiryTime);

        return () => {
            window.removeEventListener('click', updateExpiryTime);
            window.removeEventListener('keypress', updateExpiryTime);
            window.removeEventListener('scroll', updateExpiryTime);
            window.removeEventListener('mousemove', updateExpiryTime);
        };
    }, []);

    return null; 
};

export default InactivityLogoutTimer;
```

**Conclusion: Keep Your Fortress Safe**

By adding automatic logout to your React app, you're taking a big step towards keeping your users' data secure. Let's keep building strong defenses and make the web a safer place for everyone.