@igxjs/node-components
v1.0.11
Published
Node components for igxjs
Downloads
1,149
Readme
Node Components
Shared components for Express.js applications providing session management, routing utilities, error handling, JWT authentication, and Redis integration.
Installation
npm install @igxjs/node-componentsComponents
| Component | Description | Documentation | |-----------|-------------|---------------| | SessionManager | SSO session management with Redis/memory storage, supporting both session and token-based authentication | View docs | | FlexRouter | Flexible routing with context paths and middleware | View docs | | RedisManager | Redis connection management with TLS support | View docs | | JWT Manager | Secure JWT encryption/decryption with JWE | View docs | | HTTP Handlers | Standardized error handling and status codes | View docs |
Quick Start Examples
SessionManager
import { SessionManager, SessionMode } from '@igxjs/node-components';
// Create singleton instance with SESSION authentication (default)
export const session = new SessionManager({
SSO_ENDPOINT_URL: process.env.SSO_ENDPOINT_URL,
SSO_CLIENT_ID: process.env.SSO_CLIENT_ID,
SSO_CLIENT_SECRET: process.env.SSO_CLIENT_SECRET,
SESSION_SECRET: process.env.SESSION_SECRET,
REDIS_URL: process.env.REDIS_URL
});
// Create singleton instance with TOKEN authentication
export const tokenSession = new SessionManager({
SESSION_MODE: SessionMode.TOKEN, // Use token-based authentication
SSO_ENDPOINT_URL: process.env.SSO_ENDPOINT_URL,
SSO_CLIENT_ID: process.env.SSO_CLIENT_ID,
SSO_CLIENT_SECRET: process.env.SSO_CLIENT_SECRET,
SESSION_SECRET: process.env.SESSION_SECRET,
REDIS_URL: process.env.REDIS_URL,
});
// Setup in your app
await session.setup(app, (user) => ({ ...user, displayName: user.email }));
// Protect routes
app.get('/protected', session.authenticate(), (req, res) => {
res.json({ user: req.user });
});📖 Full SessionManager Documentation
FlexRouter
import { Router } from 'express';
import { FlexRouter } from '@igxjs/node-components';
const apiRouter = Router();
apiRouter.get('/users', (req, res) => res.json({ users: [] }));
// Mount with context path and middleware
const flexRouter = new FlexRouter('/api/v1', apiRouter, [authenticate]);
flexRouter.mount(app, '');📖 Full FlexRouter Documentation
JWT Manager
import { JwtManager } from '@igxjs/node-components';
const jwt = new JwtManager({ expirationTime: '1h' });
const SECRET = process.env.JWT_SECRET;
// Create token
const token = await jwt.encrypt({ userId: '123', email: '[email protected]' }, SECRET);
// Verify token
const { payload } = await jwt.decrypt(token, SECRET);📖 Full JWT Manager Documentation
HTTP Handlers
import {
httpCodes,
httpError,
httpErrorHandler,
httpNotFoundHandler
} from '@igxjs/node-components';
// Use in routes
app.get('/api/data', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (error) {
next(httpError(httpCodes.SYSTEM_FAILURE, 'Failed to fetch data', error));
}
});
// Add middleware
app.use(httpNotFoundHandler);
app.use(httpErrorHandler);📖 Full HTTP Handlers Documentation
SessionManager Authentication Modes
The SessionManager supports two authentication modes:
SESSION Mode (Default)
Uses traditional server-side session cookies. When a user authenticates via SSO, their session is stored in Redis or memory storage. The client sends the session cookie with each request to prove authentication.
Configuration:
SESSION_MODE:SessionMode.SESSION(default) - Uses session-based authenticationSESSION_AGE: Session timeout in milliseconds (default: 64800000)REDIS_URL: Redis connection string for session storage
Auth Methods:
session.authenticate()- Protect routes with SSO session verificationsession.verifySession(isDebugging, redirectUrl)- Explicit session verification methodsession.logout(redirect?, all?)- Logout current session (or logout all for token mode)
TOKEN Mode
Uses JWT bearer tokens instead of session cookies. When a user authenticates via SSO, a JWT token is generated and stored in Redis. The client includes the token in the Authorization header (Bearer {token}) with each request.
Configuration:
SESSION_MODE:SessionMode.TOKEN- Uses token-based authenticationSSO_SUCCESS_URL: Redirect URL after successful SSO loginSSO_FAILURE_URL: Redirect URL after failed SSO loginJWT_ALGORITHM: JWT algorithm (default:'dir')JWT_ENCRYPTION: Encryption algorithm (default:'A256GCM')JWT_EXPIRATION_TIME: Token expiration time (default:'10m')JWT_CLOCK_TOLERANCE: Clock skew tolerance in seconds (default: 30)
Auth Methods:
session.verifyToken(isDebugging, redirectUrl)- Protect routes with token verificationsession.callback(initUser)- SSO callback handler for token generationsession.refresh(initUser)- Refresh user authentication based on auth modesession.logout(redirect?, all?)- Logout current or all tokens
Token Storage (Client-Side):
When using token-based authentication, the client-side HTML page stores the token in localStorage:
<script>
// Store auth data in localStorage
localStorage.setItem('authToken', ${JSON.stringify(token)});
localStorage.setItem('tokenExpiry', ${Date.now() + sessionAge});
localStorage.setItem('user', ${JSON.stringify({
email: user.email,
name: user.name,
})});
// Redirect to original destination
window.location.replace(redirectUrl);
</script>SessionManager Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| SSO_ENDPOINT_URL | string | - | Identity provider endpoint URL |
| SSO_CLIENT_ID | string | - | SSO client ID |
| SSO_CLIENT_SECRET | string | - | SSO client secret |
| SSO_SUCCESS_URL | string | - | Redirect URL after successful login (token mode) |
| SSO_FAILURE_URL | string | - | Redirect URL after failed login (token mode) |
| SESSION_MODE | string | SessionMode.SESSION | Authentication mode: SessionMode.SESSION or SessionMode.TOKEN |
| SESSION_AGE | number | 64800000 | Session timeout in milliseconds |
| SESSION_COOKIE_PATH | string | '/' | Session cookie path |
| SESSION_SECRET | string | - | Session/JWT secret key |
| SESSION_PREFIX | string | 'ibmid:' | Redis session/key prefix |
| REDIS_URL | string | - | Redis connection URL (optional) |
| REDIS_CERT_PATH | string | - | Path to Redis TLS certificate |
| JWT_ALGORITHM | string | 'dir' | JWT signing algorithm |
| JWT_ENCRYPTION | string | 'A256GCM' | JWE encryption algorithm |
| JWT_EXPIRATION_TIME | string | '10m' | Token expiration duration |
| JWT_CLOCK_TOLERANCE | number | 30 | Clock skew tolerance in seconds |
| JWT_SECRET_HASH_ALGORITHM | string | 'SHA-256' | Algorithm for hashing secrets |
| JWT_ISSUER | string | - | JWT issuer identifier |
| JWT_AUDIENCE | string | - | JWT audience identifier |
| JWT_SUBJECT | string | - | JWT subject identifier |
Features
- ✅ SSO Integration - Full SSO support with Redis or memory storage
- ✅ Dual Authentication Modes - SESSION (cookies) or TOKEN (Bearer tokens)
- ✅ Token Refresh - Automatic token refresh via SSO endpoints
- ✅ Session Refresh Locks - Prevent concurrent token/session refresh attacks
- ✅ JWT Security - Encrypted JWT tokens using JWE (jose library)
- ✅ Flexible Routing - Easy mounting with context paths and middleware
- ✅ Redis Support - TLS/SSL and automatic reconnection
- ✅ Error Handling - Standardized HTTP responses
- ✅ TypeScript - Complete type definitions included
- ✅ Production Ready - Session locking, auto-reconnection, error handling
Requirements
- Node.js >= 18
- Express.js >= 4.x
- Redis (optional, for session storage)
TypeScript Support
This package includes TypeScript definitions:
import type {
SessionManager,
SessionConfig,
JwtManager,
FlexRouter,
RedisManager,
CustomError
} from '@igxjs/node-components';Documentation
📚 Complete Documentation - Detailed guides for all components
- SessionManager Documentation - Comprehensive SSO session management guide
- FlexRouter Documentation - Advanced routing patterns
- RedisManager Documentation - Redis connection management
- JWT Manager Documentation - Token authentication guide
- HTTP Handlers Documentation - Error handling utilities
