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...
};
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('/');
}
};
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());
};
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(() => {
const events = ['click', 'keypress', 'scroll', 'mousemove'];
const update = () => {
updateExpiryTime();
};
events.forEach(event => window.addEventListener(event, update));
return () => {
events.forEach(event => window.removeEventListener(event, update));
};
}, []);
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(() => {
const events = ['click', 'keypress', 'scroll', 'mousemove'];
const update = () => {
updateExpiryTime();
};
events.forEach(event => window.addEventListener(event, update));
return () => {
events.forEach(event => window.removeEventListener(event, update));
};
}, []);
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.
Top comments (0)