Open reboottime opened 5 months ago
user session management on frontend side: https://www.npmjs.com/package/react-idle-timer
[
"mousemove",
"keydown",
"wheel",
"DOMMouseScroll",
"mousewheel",
"mousedown",
"touchstart",
"touchmove",
"MSPointerDown",
"MSPointerMove",
"visibilitychange",
];
react-idle-timer
sample codeIn a production app, the session validity and idle time are configurable. so you will need to derive the MAX_IDLE_TIME
from the session validity time and sometime to remind user to take action.
If user clicks the stay logged in
button, frontend makes request to backend side to extend the session time.
const [showIdleDialog, setShowIdleDialog] = useState(false);
const { start, reset } = useIdleTimer({
startManually: true,
timeout: MAX_IDLE_TIME,
onIdle: () => {
setShowIdleDialog(true);
});
// Apply your logic to start/rset the timer programatically
import { useEffect, useRef, useState } from 'react';
import Button from './ui/button';
import Dialog, { DialogContent, DialogFooter, DialogTitle } from './ui/dialog';
const IdleDialog = ({ onStayLoggedIn, onLogout }: IdleDialogProps) => {
const timerRef = useRef<ReturnType<typeof setInterval> | undefined>();
const [remainingTime, setRemainingTime] = useState(60);
useEffect(() => {
timerRef.current = setInterval(() => {
setRemainingTime((prev) => {
const nextTime = prev - 1;
if (nextTime <= 0) {
clearInterval(timerRef.current);
onLogout();
}
return nextTime;
});
}, 1000);
return () => {
clearInterval(timerRef.current);
};
}, [onLogout]);
return (
<Dialog open>
<DialogContent className='border border-brand'>
<DialogTitle>Reminder</DialogTitle>
<p className='text-dark mb-6'>
You have been inactive for a while. To secure your data, you will be
logged out in{' '}
<span className='font-bold text-xl text-brand'>{remainingTime}</span>{' '}
seconds.
</p>
<DialogFooter className='flex justify-end'>
<Button onClick={onLogout} variant='outline'>
Logout
</Button>
<Button
onClick={() => {
onStayLoggedIn();
clearTimeout(timerRef.current);
setRemainingTime(60);
}}
>
Stay Logged In
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export default IdleDialog;
interface IdleDialogProps {
onLogout: () => void;
onStayLoggedIn: () => void;
}
Overview
This article covers topic - build secure react app, together some general tips
Content