express-pulse
v0.0.8
Published
A TypeScript library for safe display and sanitization to prevent XSS attacks.
Readme
Express Pulse - Endpoints Setup Guide
Installation
npm install express-pulse typeorm pg
npm install --save-dev @types/nodeBasic Setup
1. Import Required Modules
import express from 'express';
import { DataSource } from 'typeorm';
import { setup, setupResponseTimingMiddleware } from 'express-pulse';2. Configure Express App
const app = express();
// Optional: Add response timing middleware
setupResponseTimingMiddleware(app);3. Setup Database Connection
const dataSource = new DataSource({
type: 'postgres',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
synchronize: false, // Don't use in production
logging: false,
});4. Configure Health Options
const healthOptions = {
serviceName: 'my-service',
version: '1.0.0',
checksTimeoutMs: 5000,
development: process.env.NODE_ENV !== 'production'
};5. Setup Health Endpoints
async function startServer() {
try {
// Initialize database connection
await dataSource.initialize();
// Setup health check endpoints
await setup(app, dataSource, healthOptions);
// Start server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
console.log(`Health endpoints available at:`);
console.log(` - GET /api/ping`);
console.log(` - GET /api/ready`);
console.log(` - GET /api/health`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
}
startServer();Available Endpoints
/api/ping - Liveness Probe
Purpose: Quick health check to verify the API is responding
Response: 200 OK
{
"status": "ok",
"message": "API is alive",
"timestamp": "2025-01-15T10:30:00.000Z",
"responseTimeMs": 0.15,
"client": {
"ip": "127.0.0.1",
"userAgent": "curl/7.68.0"
}
}/api/ready - Readiness Probe
Purpose: Check if the service is ready to handle requests (includes database connectivity)
Response: 200 OK (ready) or 503 Service Unavailable (not ready)
{
"success": true,
"service": "my-service",
"version": "1.0.0",
"development": false,
"timestamp": "2025-01-15T10:30:00.000Z",
"checks": {
"database": {
"status": "up",
"ok": true,
"durationMs": 12.34,
"metrics": {
"totalQueries": 42,
"avgResponseTime": 15.5,
"recentQueries": [...]
}
}
},
"responseTimeMs": 25.67
}/api/health - Comprehensive Health Check
Purpose: Detailed system and application health information
Response: 200 OK (healthy) or 503 Service Unavailable (unhealthy)
{
"success": true,
"service": "my-service",
"version": "1.0.0",
"development": false,
"uptimeSeconds": 3600,
"timestamp": "2025-01-15T10:30:00.000Z",
"host": "server-001",
"metrics": {
"system": {
"memoryUsage": {
"rss": 45678592,
"heapTotal": 29360128,
"heapUsed": 20000000
},
"loadAvg": [0.1, 0.05, 0.01]
},
"database": {
"totalQueries": 150,
"avgResponseTime": 45.2,
"recentQueries": [...]
}
},
"checks": {
"database": {
"status": "up",
"ok": true,
"durationMs": 8.91
}
},
"responseTimeMs": 45.23
}Environment Variables
Create a .env file:
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=your_username
DB_PASSWORD=your_password
DB_NAME=your_database
PORT=3000
NODE_ENV=productionDocker Integration
Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "dist/index.js"]Docker Compose
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DB_HOST=postgres
- DB_USERNAME=myuser
- DB_PASSWORD=mypass
- DB_NAME=mydb
depends_on:
- postgres
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/api/ping"]
interval: 30s
timeout: 10s
retries: 3
postgres:
image: postgres:15
environment:
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypass
POSTGRES_DB: mydbKubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-service
spec:
replicas: 3
selector:
matchLabels:
app: my-service
template:
metadata:
labels:
app: my-service
spec:
containers:
- name: app
image: my-service:latest
ports:
- containerPort: 3000
env:
- name: DB_HOST
value: "postgres-service"
livenessProbe:
httpGet:
path: /api/ping
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /api/ready
port: 3000
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3Load Balancer Health Checks
AWS Application Load Balancer
- Health Check Path:
/api/ready - Success Codes:
200 - Timeout: 5 seconds
- Interval: 30 seconds
NGINX Upstream Health Check
upstream backend {
server app1:3000;
server app2:3000;
}
location /health {
access_log off;
proxy_pass http://backend/api/ready;
proxy_set_header Host $host;
}Testing Endpoints
# Test ping endpoint
curl http://localhost:3000/api/ping
# Test readiness
curl http://localhost:3000/api/ready
# Test health with pretty output
curl -s http://localhost:3000/api/health | jq '.'
# Check response headers
curl -I http://localhost:3000/api/healthComplete Example
import express from 'express';
import { DataSource } from 'typeorm';
import { setup, setupResponseTimingMiddleware } from 'express-pulse';
const app = express();
// Add timing middleware
setupResponseTimingMiddleware(app);
// Database configuration
const dataSource = new DataSource({
type: 'postgres',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
// Health options
const healthOptions = {
serviceName: process.env.SERVICE_NAME || 'my-service',
version: process.env.SERVICE_VERSION || '1.0.0',
checksTimeoutMs: 5000,
development: process.env.NODE_ENV !== 'production'
};
async function bootstrap() {
try {
await dataSource.initialize();
console.log('Database connected');
await setup(app, dataSource, healthOptions);
console.log('Health endpoints configured');
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`🚀 Server running on port ${port}`);
console.log(`📊 Health endpoints:`);
console.log(` GET http://localhost:${port}/api/ping`);
console.log(` GET http://localhost:${port}/api/ready`);
console.log(` GET http://localhost:${port}/api/health`);
});
} catch (error) {
console.error('Failed to start application:', error);
process.exit(1);
}
}
bootstrap();Troubleshooting
Common Issues
Database Connection Fails
# Check if PostgreSQL is running pg_isready -h localhost -p 5432 # Verify connection string psql -h localhost -p 5432 -U username -d databaseHealth Checks Return 503
- Verify database connectivity
- Check timeout settings
- Review application logs
Performance Issues
- Monitor the
/api/healthmetrics - Check database query performance
- Review system resource usage
- Monitor the
Monitoring
Set up monitoring for your health endpoints:
# Monitor endpoint availability
watch -n 5 'curl -s http://localhost:3000/api/health | jq ".success"'
# Check response times
curl -w "@curl-format.txt" -s -o /dev/null http://localhost:3000/api/healthCreate curl-format.txt:
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n