ng-idle

repository·master·Indexed 43 days ago

https://github.com/grbsk/ng2-idle

A modular Angular library for detecting user idle states, managing session timeouts, and providing mechanisms to keep sessions alive via server pings. Version 16.0.0 includes the @ng-idle/core package for activity monitoring and an optional @ng-idle/keepalive module for server-side session management. It supports multi-tab coordination via LocalStorageExpiry, custom interrupt sources for activity detection, and is compatible with Angular Universal/SSR.

Tokens
6.3K
Snippets
27
Records
33
Agent score
55%

What's inside ng-idle

  1. Integrate @ng-idle/keepalive for session management

    master

    If you need to periodically signal to your server that a user is still active (to prevent server-side session expiration), you can use the optional @ng-idle/keepalive module.

    When integrated, @ng-idle will automatically instruct @ng-idle/keepalive to ping the server while the user is active and stop once the user becomes idle or times out. It also triggers an immediate ping when a user resumes activity.

  2. Compatibility with Server-Side Rendering (SSR/Universal)

    master

    Since @ng-idle relies on DOM events, it is designed to be compatible with Angular Universal/SSR.

    Interrupt sources derived from EventTargetInterruptSource (including DocumentInterruptSource, WindowInterruptSource, and StorageInterruptSource) use lazy initialization. They check if the application is running in the browser (using isPlatformServer) and will skip initializing event listeners when running on the server to prevent crashes caused by accessing document or window globals.

  3. Configure Expiry strategies

    master

    Expiry determines how the idle state is tracked and how it handles multi-tab scenarios.

    Available strategies:

    • LocalStorageExpiry (Default): Stores the expiry value in localStorage. This allows multiple tabs or windows of the same application to coordinate; activity in one tab prevents others from timing out.
    • SimpleExpiry: Does not coordinate activity between tabs or windows. Use this if you only want to track idle state within a single tab.

    You can implement custom expiry logic by extending IdleExpiry or SimpleExpiry and providing it as a provider for the IdleExpiry class.

  4. How @ng-idle works: Core concepts

    master

    The primary purpose of @ng-idle is to detect when users are idle, warn them of impending timeouts, and perform actions (like logging out) when a timeout occurs.

    At its center is the Idle service, which monitors user activity based on your configuration and notifies your application of state changes.

    Key components include:

    • Interrupts: Sources of input (like clicks or typing) that reset the idle timer.
    • Expiry: Mechanisms to track when a session should expire, which can be coordinated across multiple browser tabs.
    • Keepalive: An optional integration to signal the server that a user is still active.
  5. Publish the keepalive library

    master

    To publish the library to npm, you must first build it, navigate to the distribution folder, and then run the publish command.

    1. Build the project: ng build keepalive
    2. Change directory to the build output: cd dist/keepalive
    3. Publish: npm publish
    ng build keepalive
    cd dist/keepalive
    npm publish
  6. Use multiple Idle instances

    master

    Because @ng-idle leverages Angular's hierarchical dependency injection, you can create multiple instances of the Idle service at different scopes (e.g., to monitor different elements independently).

    Important: If you are using the default LocalStorageExpiry, you must assign a unique name to each instance using Idle.setIdleName('yourIdleName'). If names are not unique, they will overwrite each other in localStorage, breaking the multi-instance functionality.

    // Example for a specific instance
    Idle.setIdleName('myUniqueIdleInstance');
  7. Install @ng-idle/core via npm

    master

    To use the core functionality of the ng2-idle module for detecting user idle states in Angular applications, install the @ng-idle/core package using npm.

    npm install --save @ng-idle/core
  8. Generate code in the keepalive project

    master

    To generate new Angular entities (components, directives, pipes, services, etc.) specifically within the keepalive project, use the Angular CLI with the --project keepalive flag. Failing to include this flag will cause the entity to be added to the default project defined in your angular.json.

    ng generate component component-name --project keepalive
    # Or for other types:
    ng generate directive|pipe|service|class|guard|interface|enum|module --project keepalive
  9. Configure ng-idle/keepalive in Angular

    master

    To use the @ng-idle/keepalive package in an Angular application using standalone components and the ApplicationConfig pattern, you must include provideNgIdleKeepalive() in your providers array.

    If you are using the keepalive feature (which typically involves making HTTP requests to keep a session alive), you must also provide the HttpClient using provideHttpClient().

    import { ApplicationConfig } from '@angular/core';
    import { provideHttpClient, withFetch } from '@angular/common/http';
    import { provideNgIdleKeepalive } from '@ng-idle/keepalive';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideNgIdleKeepalive(),
        provideHttpClient(withFetch())
      ]
    };
  10. Configure Interrupt Sources

    master

    An interrupt is an input source that signals the Idle service to reset the idle watch. By default, no interrupts are configured. You must explicitly configure them during application initialization.

    Built-in interrupt sources include:

    • InterruptSource (abstract): Base type for custom implementations.
    • EventTargetInterruptSource: Targets any EventTarget (e.g., HTMLElement, Window) using a space-delimited string of event names.
    • DocumentInterruptSource: Listens for events bubbling up to document.documentElement.
    • WindowInterruptSource: Listens for events bubbling up to the Window.
    • StorageInterruptSource: Listens specifically for the Storage event on the Window object (required for LocalStorageExpiry).

    To use the default set of interrupts, import DEFAULT_INTERRUPTSOURCES and pass it to the service:

    Idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);