Skip to main content

How to Handle User Idleness and Session Timeout in Angular

There are times you need to handle auto-logout or session timeout (session expired) in your angular application based on user inactivity for a specific period of time. In this tutorial, I will teach you how to handle user idleness using bn-ng-idle npm package.

Install bn-ng-idle Session Timeout NPM package

npm install bn-ng-idle --save
The package exports a singleton service BnNgIdleService which is written in RxJS to listen for various DOM elements, Import the service in your module and add it in your providers array.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { BnNgIdleService } from 'bn-ng-idle'; // import bn-ng-idle service
 
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [BnNgIdleService], // add it to the providers of your module
  bootstrap: [AppComponent]
})
export class AppModule { }

Listen for User Idleness/Session Timeout in Angular Component

Let’s listen for the user’s idleness in an angular component.
  • Import the BnNgIdleService in your component
  • Inject the service in the constructor to create a singleton instance.
import { Component } from '@angular/core';
import { BnNgIdleService } from 'bn-ng-idle'; // import it to your component
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  constructor(private bnIdle: BnNgIdleService) {
 
  }
 
  // initiate it in your component OnInit
  ngOnInit(): void {
    this.bnIdle.startWatching(60).subscribe((isTimedOut: boolean) => {
      if (isTimedOut) {
        console.log('session expired');
      }
    });
  }
}
In your ngOnInit lifecycle hook, subscribe to the startWatching method which returns an observable.
The startWatching method accepts a single parameter that is the time duration in seconds.
In the above example, I have passed 60 seconds (1 minute). If the user is idle for the specified minutes, then the observable will be emitted by the service. Based on the value of isTimedOut (boolean), We can do auto-logout or an API call or some redirection, etc. For brevity, I just logged the text.

Under the Hood – Session Timeout Logic in Angular

In-depth, the bn-ng-idle package is written in RxJS to listen for various DOM events like mouse move, click, resize, etc.
A timer will run once you subscribed to startWatching method, if there’s an event the timer gets restarted automatically inside the package.
If there’s no event triggered for the specified time, the startWatching method will emit the boolean value to indicate that the user is inactive.

Conclusion

I hope, you got a solution for your angular application to handle session timeout (session expired) based on user idleness/user inactivity. If you know any other package which suits best for this user idleness/session timeout scenario, make a comment below.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...