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

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/node

Basic 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=production

Docker 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: mydb

Kubernetes 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: 3

Load 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/health

Complete 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

  1. 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 database
  2. Health Checks Return 503

    • Verify database connectivity
    • Check timeout settings
    • Review application logs
  3. Performance Issues

    • Monitor the /api/health metrics
    • Check database query performance
    • Review system resource usage

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/health

Create 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