npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ngxsmk-gatekeeper

v1.2.0

Published

A framework-agnostic middleware engine for Angular that provides route and HTTP request protection through a composable middleware pattern

Downloads

170

Readme

ngxsmk-gatekeeper - The Ultimate Angular Route & HTTP Protection Library

npm version npm downloads Angular License: MIT TypeScript Security Policy

Stop writing duplicate route guards and HTTP interceptors. Start protecting your Angular app in 30 seconds.

ngxsmk-gatekeeper is the most powerful, developer-friendly middleware engine for Angular. Protect routes and HTTP requests with a single, composable configuration. 100% open source. Zero dependencies. Production-ready.

What's New in v1.2.0

  • Angular 22 / TypeScript 6 Support - Toolchain upgraded to @angular/build@22, ng-packagr@22, and TypeScript 6.0. Tested across Angular 17-22.
  • Dedicated Testing Entry Point - All test helpers, mock contexts, and assertions now ship via the ngxsmk-gatekeeper/testing secondary entry point for tree-shakeable, test-only imports.
  • Cache Middleware next Option - createCacheMiddleware can wrap a downstream middleware and cache its allow/deny result (see cacheOnlySuccess).
  • Expanded Test Coverage - Comprehensive unit tests for the Gatekeeper Agent and core middleware (97+ tests passing).

Why Developers Love This Library

The Problem: You're writing custom guards for routes, separate interceptors for HTTP, duplicating logic, and struggling to compose protection rules.

The Solution: One middleware pattern. One configuration. Works everywhere. Type-safe. Tree-shakeable. Zero bloat.

Get Protected in 30 Seconds

npm install ngxsmk-gatekeeper
import { provideGatekeeper, gatekeeperGuard } from 'ngxsmk-gatekeeper';
import { createAuthMiddleware } from 'ngxsmk-gatekeeper';

// 1. Create middleware (one line)
const authMiddleware = createAuthMiddleware({ authPath: 'user.isAuthenticated' });

// 2. Configure (one provider)
bootstrapApplication(AppComponent, {
  providers: [provideGatekeeper({ middlewares: [authMiddleware], onFail: '/login' })],
});

// 3. Protect routes (one guard)
const routes: Routes = [
  {
    path: 'dashboard',
    canActivate: [gatekeeperGuard],
    loadComponent: () => import('./dashboard.component'),
  },
];

Done. Your routes are protected. HTTP requests too. No boilerplate. No duplication.

What Makes This Special?

Built for Angular Developers

  • Next.js Middleware Experience - If you love Next.js middleware, you'll love this
  • Functional API - Modern Angular 17+ patterns, no legacy code
  • Standalone-Only - Built for the future of Angular
  • TypeScript First - Full type safety, autocomplete, zero runtime errors

Performance That Matters

  • Tree-Shakeable - Only bundle what you use (zero overhead)
  • Zero Dependencies - Lightweight core, no bloat
  • Optimized Execution - Fast middleware chains, minimal overhead
  • Built-in Benchmarking - Identify bottlenecks automatically
  • Angular Signals - Fully optimized for Angular Signals (17+)
  • SEO Friendly - Doesn't block crawlers; supports proper status codes and redirects

Developer Experience That Delights

  • Debug Mode - See exactly what's happening in your middleware
  • Composable - Build complex logic from simple pieces
  • Flexible - Sync, Promise, or Observable - your choice
  • Well-Documented - Comprehensive docs with real examples

Key Features

Core Features

| Feature | Description | Status | | --------------------------- | ------------------------------------- | ---------------- | | Route Protection | Protect routes with functional guards | Production Ready | | HTTP Protection | Protect API calls with interceptors | Production Ready | | Composable Middleware | Chain middleware like Next.js | Production Ready | | Type-Safe | Full TypeScript support | Production Ready | | Tree-Shakeable | Zero bundle overhead | Production Ready | | Debug Mode | Built-in debugging and benchmarking | Production Ready | | Authentication Adapters | Auth0, Firebase, JWT support | Included | | Compliance Mode | SOC2, ISO 27001 ready | Included | | Plugin Architecture | Extensible and customizable | Included |

Developer Tools

| Feature | Description | Status | | ----------------------------- | ------------------------------------------------- | --------- | | Angular Schematics | Code generators for middleware and pipelines | Available | | Interactive Playground | Try it live in StackBlitz/CodeSandbox | Available | | Standalone CLI Tool | Init, analyze, test, and export commands | Available | | Testing Utilities | Mock contexts, assertions, and test helpers | Available | | Configuration Validator | Type checking, performance, and security analysis | Available | | Visual Middleware Builder | Drag-and-drop interface for building middleware | Available | | Real-time Observability | WebSocket monitoring and analytics dashboard | Available | | Template Library | Pre-built configurations for common scenarios | Available | | Middleware Marketplace | Discover and install community plugins | Available | | Showcase Gallery | Real-world implementations and case studies | Available |

Security Middleware (8 features)

  • IP Whitelisting/Blacklisting - Allow/block specific IPs or CIDR ranges
  • CSRF Protection - Protect against Cross-Site Request Forgery
  • Session Management - Automatic session timeout and renewal
  • API Key Validation - Protect APIs with key validation
  • Account Lockout - Brute force protection
  • Webhook Signature Verification - Verify webhook signatures
  • Device Fingerprinting - Track and validate devices
  • User-Agent Validation - Block bots and validate browsers

Access Control (3 features)

  • Time-Based Access - Restrict access by time/day
  • Maintenance Mode - Enable maintenance with admin access
  • Geographic Restrictions - Block/allow by country

Authentication (3 features)

  • Multi-Factor Authentication (MFA) - Enforce MFA
  • OAuth2/OIDC - OAuth2 authentication support
  • JWT Token Refresh - Automatic token renewal

Request Processing (4 features)

  • Request Validation - Validate body, query, params, headers
  • Request Size Limits - Prevent DoS attacks
  • Request Deduplication - Prevent duplicate requests
  • API Versioning - Handle API versioning

Advanced Control (4 features)

  • Conditional Middleware - If/else logic in chains
  • Circuit Breaker - Resilience pattern
  • Retry Logic - Retry with backoff strategies
  • Concurrent Limits - Limit concurrent requests

Analytics & Monitoring (3 features)

  • Request Analytics - Track metrics and events
  • A/B Testing - Implement A/B tests
  • Request Logging - Comprehensive request logging

Performance (2 features)

  • Cache Middleware - Cache middleware results
  • Request Batching - Batch requests together

Real-World Examples

Authentication Protection

import { createAuthMiddleware } from 'ngxsmk-gatekeeper';

const authMiddleware = createAuthMiddleware({
  authPath: 'user.isAuthenticated',
});

provideGatekeeper({
  middlewares: [authMiddleware],
  onFail: '/login',
});

Using Templates

import { createTemplateLoader } from 'ngxsmk-gatekeeper';

const loader = createTemplateLoader();

// Create configuration from template
const config = await loader.createConfig('saas', {
  roles: ['user', 'admin'],
  enableRateLimit: true,
});

provideGatekeeper(config);

Role-Based Access Control

import { createAuthMiddleware, createRoleMiddleware } from 'ngxsmk-gatekeeper';
import { definePipeline } from 'ngxsmk-gatekeeper';

// Create reusable pipeline
const adminPipeline = definePipeline('adminOnly', [
  createAuthMiddleware(),
  createRoleMiddleware({ roles: ['admin'], mode: 'any' }),
]);

// Use in routes
const routes: Routes = [
  {
    path: 'admin',
    canActivate: [gatekeeperGuard],
    data: { gatekeeper: { middlewares: [adminPipeline] } },
  },
];

HTTP Request Protection

import { gatekeeperInterceptor } from 'ngxsmk-gatekeeper';
import { provideHttpClient, withInterceptors } from '@angular/common/http';

// Same middleware works for HTTP too!
provideHttpClient(withInterceptors([gatekeeperInterceptor]));

Security Features

import {
  createIPWhitelistMiddleware,
  createCSRFMiddleware,
  createSessionMiddleware,
  createAPIKeyMiddleware,
} from 'ngxsmk-gatekeeper';

const securityPipeline = definePipeline('security', [
  createIPWhitelistMiddleware({ allowedIPs: ['10.0.0.0/8'] }),
  createCSRFMiddleware({ tokenHeader: 'X-CSRF-Token' }),
  createSessionMiddleware({ timeout: 3600 }),
  createAPIKeyMiddleware({ validateKey: async (key) => await checkKey(key) }),
]);

Access Control

import {
  createTimeWindowMiddleware,
  createMaintenanceModeMiddleware,
  createGeoBlockMiddleware,
  DayOfWeek,
} from 'ngxsmk-gatekeeper';

const accessControl = definePipeline('access', [
  createTimeWindowMiddleware({
    allowedHours: { start: 9, end: 17 },
    allowedDays: [DayOfWeek.Monday, DayOfWeek.Friday],
  }),
  createMaintenanceModeMiddleware({ enabled: false }),
  createGeoBlockMiddleware({ allowedCountries: ['US', 'CA'] }),
]);

Monitoring & Analytics

import {
  createAnalyticsMiddleware,
  createABTestMiddleware,
  createRequestLoggingMiddleware
} from 'ngxsmk-gatekeeper';

const monitoring = definePipeline('monitoring', [
  createAnalyticsMiddleware({ sink: analyticsSink }),
  createABTestMiddleware({ tests: { 'feature': { variants: [...] } } }),
  createRequestLoggingMiddleware({ logLevel: 'info' })
]);

Perfect For

  • Enterprise Applications - SOC2, ISO compliance ready
  • SaaS Products - Multi-tenant, role-based access
  • E-commerce - Payment protection, cart security
  • Admin Dashboards - Complex permission systems
  • Public APIs - Rate limiting, authentication
  • Any Angular App - That needs route or HTTP protection

Why Choose ngxsmk-gatekeeper?

vs. Writing Custom Guards

| Custom Guards | ngxsmk-gatekeeper | | ----------------------------------- | -------------------------------- | | Duplicate logic for routes and HTTP | One middleware, works everywhere | | Hard to compose and reuse | Composable pipelines | | No type safety | Full TypeScript support | | Difficult to debug | Built-in debug mode | | No performance insights | Built-in benchmarking |

vs. Other Libraries

  • More Flexible - Works with sync, Promise, and Observable
  • Better DX - Debug mode, benchmarking, type safety
  • Zero Dependencies - Lighter than alternatives
  • Modern API - Functional guards, standalone-only
  • Production Ready - Used in real applications

Quick Start Guide

Step 1: Install

npm install ngxsmk-gatekeeper

Step 2: Configure

import { provideGatekeeper } from 'ngxsmk-gatekeeper';
import { createAuthMiddleware } from 'ngxsmk-gatekeeper';

bootstrapApplication(AppComponent, {
  providers: [
    provideGatekeeper({
      middlewares: [createAuthMiddleware()],
      onFail: '/login',
    }),
  ],
});

Step 3: Protect Routes

import { gatekeeperGuard } from 'ngxsmk-gatekeeper';

const routes: Routes = [
  {
    path: 'dashboard',
    canActivate: [gatekeeperGuard],
    loadComponent: () => import('./dashboard.component'),
  },
];

Step 4: Protect HTTP (Optional)

import { gatekeeperInterceptor } from 'ngxsmk-gatekeeper';
import { provideHttpClient, withInterceptors } from '@angular/common/http';

provideHttpClient(withInterceptors([gatekeeperInterceptor]));

That's it! Your app is now protected.

Complete Documentation

Advanced Features

Debug Mode

See exactly what's happening:

provideGatekeeper({
  middlewares: [authMiddleware],
  debug: true, // Enable debug logging
});

Output:

[Gatekeeper] Chain started: /dashboard
[Gatekeeper] Middleware[0] (auth): ✓ Passed (2.3ms)
[Gatekeeper] Chain completed: ✓ Allowed (3.4ms)

Performance Benchmarking

Identify bottlenecks automatically:

provideGatekeeper({
  middlewares: [authMiddleware],
  benchmark: {
    enabled: true,
    middlewareThreshold: 100, // Warn if > 100ms
    chainThreshold: 500, // Warn if > 500ms
  },
});

Custom Middleware

Build your own protection logic:

import { createMiddleware } from 'ngxsmk-gatekeeper';

const customMiddleware = createMiddleware('custom', (context) => {
  // Your logic here
  return context.user?.hasPermission('custom-permission') ?? false;
});

Developer Tools

Angular Schematics

Generate middleware and pipelines with Angular CLI:

ng add ngxsmk-gatekeeper
ng generate ngxsmk-gatekeeper:middleware auth
ng generate ngxsmk-gatekeeper:pipeline admin

CLI Tool

Analyze and test your configuration:

npx @ngxsmk-gatekeeper/cli init
npx @ngxsmk-gatekeeper/cli analyze
npx @ngxsmk-gatekeeper/cli test

Visual Builder

Build middleware chains visually with drag-and-drop:

import { VisualBuilderService } from 'ngxsmk-gatekeeper';

const builder = new VisualBuilderService();
// Use the visual builder UI to create middleware chains

Real-time Observability

Monitor middleware execution in real-time:

import { provideObservability } from 'ngxsmk-gatekeeper';

provideObservability({
  websocketUrl: 'ws://localhost:8080',
  enableRealtime: true,
});

Template Library

Use pre-built configurations:

import { createTemplateLoader } from 'ngxsmk-gatekeeper';

const loader = createTemplateLoader();
const config = await loader.createConfig('saas', {
  roles: ['user', 'admin'],
  enableRateLimit: true,
});

Configuration Validator

Validate your setup:

import { ConfigValidator } from 'ngxsmk-gatekeeper';

const validator = inject(ConfigValidator);
const result = await validator.validate(config);
console.log(result.issues);

Testing Utilities

Test middleware easily with the dedicated ngxsmk-gatekeeper/testing entry point:

import { createMockContext, expectMiddlewareToAllow } from 'ngxsmk-gatekeeper/testing';

const context = createMockContext({ user: { isAuthenticated: true } });
await expectMiddlewareToAllow(authMiddleware(context));

All mock contexts, assertion helpers, and integration utilities are available from ngxsmk-gatekeeper/testing so test-only code never bloats your production bundle.

Learn More

Documentation

Examples

Production Ready

  • Type-Safe - Full TypeScript support
  • Tree-Shakeable - Zero bundle overhead
  • Well-Tested - Comprehensive test coverage with testing utilities
  • Well-Documented - Complete documentation with examples
  • Security-First - Responsible disclosure policy
  • Long-Term Support - Clear LTS strategy
  • Developer Tools - Schematics, CLI, visual builder, and more
  • Community - Marketplace, showcase gallery, and active development

Requirements

  • Angular 17-22 (Standalone components required)
  • TypeScript 6.0+
  • Node.js 20+ (Node 22 recommended)

Contributing

We welcome contributions! Whether it's:

  • Bug reports
  • Feature requests
  • Documentation improvements
  • Code contributions
  • Starring the repo

Read our Contributing Guide to get started.

License

MIT License - see LICENSE file for details.

100% open source. Free forever. No restrictions.

Show Your Support

If this library helps you build better Angular applications:

  • Star the repository
  • Share with your team
  • Tweet about it
  • Leave feedback

Links

Acknowledgments

Built with love for the Angular community. Inspired by Next.js middleware pattern.


Made by developers, for developers.

Questions? Open an issue or start a discussion. We're here to help!