Tuesday, December 11, 2018

How to implement Auto Logout client side in react

This tutorial explains how to implement auto logout system in client system in react application. The Auto Logout system is implemented by most of the web application nowadays, that helps users to protect their secure data from unauthorized access in case they forgot to logout their web application sessions.

So In this tutorial, we are going to share React source code to implement auto logout system. In this example we are maintaining two timestamp for user session.
  • First timestamp helps to notify alert message when user is inactive for 16 seconds.
  • Second timestamp helps to initiate logout module when user is inactive for 30 seconds.
How to implement Auto Logout client side in react

Auto Logout System When User Is Inactive In React :

Lets see the below example, that helps to build more understanding on this.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {

    this.state = { logginStatus: true };
    this.events = [

    this.warn = this.warn.bind(this);
    this.logout = this.logout.bind(this);
    this.resetTimeout = this.resetTimeout.bind(this);

    for (var i in this.events) {
      window.addEventListener(this.events[i], this.resetTimeout);


  clearTimeout() {
    if (this.warnTimeout) clearTimeout(this.warnTimeout);

    if (this.logoutTimeout) clearTimeout(this.logoutTimeout);

  setTimeout() {
    this.warnTimeout = setTimeout(this.warn, 16 * 1000);

    this.logoutTimeout = setTimeout(this.logout, 30 * 1000);

  resetTimeout() {

  warn() {
    alert("You will be logged out automatically in 1 minute.");

  logout() {
    // Send a logout request to the API
    console.log("Sending a logout request to the API...");
    this.setState({ logginStatus: false });
    // this.destroy(); // Cleanup

  destroy() {

    for (var i in this.events) {
      window.removeEventListener(this.events[i], this.resetTimeout);
  render() {
    return (
      <div className="App">
        <h1>Session auto logout after inactivity</h1>
        <h2>Status :{this.state.logginStatus ? "Loggin" : "Logout"}</h2>

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output :
Check out this link : https://codesandbox.io/s/ox8o8o53oq

This is all about auto logout system in react application. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.