DEV Community

Cover image for Enhancing React App Security: Implementing Inactivity Logout for Peace of Mind
Pratik Singh
Pratik Singh

Posted on

Enhancing React App Security: Implementing Inactivity Logout for Peace of Mind

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.

// Inside InactivityLogoutTimer.jsx
const InactivityLogoutTimer = () => {
    // Functions to check for inactivity and update expiry time...
};
Enter fullscreen mode Exit fullscreen mode

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.

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

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

3. Keeping Time: Updating Expiry

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

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

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.

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);
    };
}, []);
Enter fullscreen mode Exit fullscreen mode

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.

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;
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)