Handling session timeout in Angular

Handling session timeout in a web application for an idle user is an important part of the security management. Session timeout will be managed by the server in a traditional web application where pages are served from the server. But in an application like Angular, it will be tricky as entire source code is present in the client browser. This situation can be handled by using ng2- idle module.

ng2- idle – https://www.npmjs.com/package/ng2-idle

ng2-idle keeps track of user activities and if it finds the user is idle, it passes the information on to the application so that it can respond appropriately.

Use ng2-idle-keepalive module along with ng2-idle if you want to signal to the server periodically that the user is still active.

For instance, if you have JWT token-based security module setup in your angular application, then the validity of the token can be kept intact by contacting issuing server(like OAM server) using ng2-idle-keepalive

ng2-idle-keepalive – https://www.npmjs.com/package/ng2-idle-keepalive

Installation steps

npm install –save @ng-idle/core

npm install –save @ng-idle/keepalive

How to enable session timeout?

Setup application Module

Import Ng2IdleModule  inside Open src/app/app.module.ts.


Create timeout warning popup

Timeout warning popup will be displayed to the user for last 5 minutes out of 15 minutes of idleness. 2 options will be provided on this popup either to continue his session or option to log out. If the user didn’t take any action in 5 minutes, the user will be logged out and redirected login page.


Enable app component to watch for idleness

Inside app component constructor configure the idle service by providing following details

  • Timeout
  • Warning popup display time

In my sample, Timeout is 15 minutes out of which last 5 minutes is configured to display timeout warning popup.


Use Keepalive option to ping server

Use Keepalive request option to ping server to make session is active on the server as well. Read the ping response using onPing option. Handle response other than response status is 200 by redirecting the user to log out screen stating session is timed out.


Show warning popup

After idle time crosses certain time(say 10 min) start showing warning popup stating session will be logged out if no action has been taken. Populate timer counter using onTimeoutwarning option.


Download Source code from Github – https://github.com/programmingwithnaveen/Session-Timeout

Demo Video – https://www.youtube.com/watch?v=Gnwb0-SOHCQ


  1. https://hackedbychinese.github.io/ng2-idle/
  2. http://getbootstrap.com/
  3. https://ng-bootstrap.github.io/#/getting-started