Implementing Auto-Logout on Inactivity in React Js

  • To implement functionality in React JS that automatically logs out the user after 10 minutes of inactivity following their login, you can follow these steps. This functionality involves setting up a timer that resets with any user activity on the page and logs the user out if no activity is detected within the specified time limit. Here's how to achieve this:
Step 1: Tracking User Activity
  • To track user activities like mouse movements, clicks, keyboard inputs, and scrolling, you can use event listeners. These listeners will ensure that any user activity resets the inactivity timer.
Step 2: Setting Up the Timer
  • Whenever user activity is detected, you need to set up a timer that counts down from 10 minutes. If no further activity is detected during this period, the session should be considered expired, and the user should be logged out.
Step 3: Implementing the Logout Functionality
  • If the timer expires without detecting any activity, you'll need to implement the functionality to log the user out. This usually involves invalidating the server-side session and redirecting the user to the login page on the client side.
Implementation Example with Scroll Activity


    import React, { useEffect } from 'react';

    const LogoutTimer = () => {
        let logoutTimer;

        const handleUserActivity = () => {
            clearTimeout(logoutTimer);
            logoutTimer = setTimeout(() => {
                // Implement logout functionality here
                console.log('User logged out due to inactivity.');
                // Example: Clear user session and redirect to login page
                // sessionStorage.clear();
                // window.location.href = '/login';
            }, 600000); // 10 minutes in milliseconds
        };

        useEffect(() => {
            // Add event listeners for various user activities
            window.addEventListener('mousemove', handleUserActivity);
            window.addEventListener('keypress', handleUserActivity);
            window.addEventListener('click', handleUserActivity);
            window.addEventListener('scroll', handleUserActivity, true); // Capturing scroll activity

            // Cleanup function to remove event listeners
            return () => {
                window.removeEventListener('mousemove', handleUserActivity);
                window.removeEventListener('keypress', handleUserActivity);
                window.removeEventListener('click', handleUserActivity);
                window.removeEventListener('scroll', handleUserActivity);
                clearTimeout(logoutTimer);
            };
        }, []);

        return (
            <div>
                {/* Your application's components */}
            </div>
        );
    };

    export default LogoutTimer;

  • In this example, the `useEffect` hook is used to add and remove event listeners when the component mounts and unmounts, respectively. The `handleUserActivity` function resets the logout timer whenever the user performs any activity, including scrolling. If there's no activity for 10 minutes, the callback function for `setTimeout` executes the logout functionality.
  • This basic implementation may need adjustments based on your specific requirements, such as verifying the user's login status before setting the timer or implementing a more complex session management strategy.

No comments:

Post a Comment

How PHP Embeds Into HTML — And Can It Work Inside JavaScript?

One of PHP's most unique characteristics is that it doesn't live in its own isolated file waiting to be called. It can sit directly ...