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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@betternest/healthcheck

v1.0.0

Published

Auto-discovery health checks with decorators for NestJS

Downloads

12

Readme

@betternest/healthcheck

Auto-discovery health checks with decorators for NestJS

@betternest/healthcheck provides zero-configuration health checks for your NestJS application. Simply decorate your service methods with @HealthCheck() and they're automatically exposed at /healthz.

Features

  • Zero Configuration - Works out of the box
  • Auto-Discovery - Automatically finds all health checks
  • Type-Safe - Full TypeScript support
  • REST API - Exposes /healthz endpoints
  • Service Filtering - Check individual services
  • Version Info - Includes app version in response

Installation

npm install @betternest/healthcheck
# or
yarn add @betternest/healthcheck
# or
pnpm add @betternest/healthcheck

Quick Start

1. Import Module

import { Module } from '@nestjs/common';
import { HealthCheckModule } from '@betternest/healthcheck';

@Module({
  imports: [HealthCheckModule],
})
export class AppModule {}

2. Add Health Checks to Your Services

import { Injectable } from '@nestjs/common';
import { HealthCheck } from '@betternest/healthcheck';

@Injectable()
export class DatabaseService {
  @HealthCheck()
  protected async checkConnection() {
    const isConnected = await this.database.ping();

    if (!isConnected) {
      throw new Error('Database not connected');
    }

    return {
      connected: true,
      latency: await this.database.getLatency(),
    };
  }
}

@Injectable()
export class CacheService {
  @HealthCheck()
  protected async checkCache() {
    return {
      connected: await this.redis.ping(),
      memory: await this.redis.info('memory'),
    };
  }
}

3. That's it!

Health checks are automatically exposed:

# Check all services
curl http://localhost:3000/healthz

# Check specific service
curl http://localhost:3000/healthz/DatabaseService

API Endpoints

GET /healthz

Check all services.

Response (200 OK):

{
  "hasError": false,
  "states": {
    "DatabaseService": "OK",
    "CacheService": "OK"
  },
  "services": {
    "DatabaseService": {
      "connected": true,
      "latency": 5
    },
    "CacheService": {
      "connected": true,
      "memory": "used_memory:1024"
    }
  },
  "version": "1.0.0",
  "timestamp": "2025-01-05T12:00:00.000Z"
}

Response (500 Internal Server Error) when any check fails:

{
  "hasError": true,
  "states": {
    "DatabaseService": "ERRORED",
    "CacheService": "OK"
  },
  "services": {
    "DatabaseService": "Database not connected",
    "CacheService": {
      "connected": true
    }
  },
  "version": "1.0.0",
  "timestamp": "2025-01-05T12:00:00.000Z"
}

GET /healthz/:service

Check a specific service (e.g., /healthz/DatabaseService).

Returns the same format but filtered to that service only.

Usage

Basic Health Check

@Injectable()
export class MyService {
  @HealthCheck()
  protected async check() {
    return {
      status: 'OK',
      uptime: process.uptime(),
    };
  }
}

Health Check with Error

@Injectable()
export class ApiService {
  @HealthCheck()
  protected async checkApi() {
    const response = await fetch('https://api.example.com/health');

    if (!response.ok) {
      throw new Error(`API returned ${response.status}`);
    }

    return {
      status: 'OK',
      latency: response.headers.get('x-response-time'),
    };
  }
}

Health Check with Structured Error Data

Use HealthCheckError to return structured data even on failure:

import { HealthCheck, HealthCheckError } from '@betternest/healthcheck';

@Injectable()
export class DatabaseService {
  @HealthCheck()
  protected async checkDatabase() {
    try {
      await this.database.ping();
      return {
        connected: true,
        pool: await this.database.getPoolStatus(),
      };
    } catch (error) {
      // Return structured error data
      throw new HealthCheckError({
        connected: false,
        error: error.message,
        lastSuccessfulPing: this.lastPingTime,
      });
    }
  }
}

Response when using HealthCheckError:

{
  "hasError": true,
  "states": {
    "DatabaseService": "ERRORED"
  },
  "services": {
    "DatabaseService": {
      "connected": false,
      "error": "Connection timeout",
      "lastSuccessfulPing": "2025-01-05T11:00:00.000Z"
    }
  }
}

Best Practices

1. Use Protected Methods

Health checks should be protected (not public) to keep them internal:

@HealthCheck()
protected async check() {  // ✅ Good
  return { status: 'OK' };
}

@HealthCheck()
async check() {  // ⚠️ Works but less encapsulated
  return { status: 'OK' };
}

2. One Health Check Per Service

Each service should have exactly ONE @HealthCheck() method:

// ✅ Good
@Injectable()
export class DatabaseService {
  @HealthCheck()
  protected async check() {
    return {
      connected: await this.checkConnection(),
      migrations: await this.checkMigrations(),
    };
  }
}

// ❌ Bad - Multiple health checks in one service
@Injectable()
export class DatabaseService {
  @HealthCheck()
  protected async checkConnection() { }

  @HealthCheck()  // ERROR: Duplicate health check!
  protected async checkMigrations() { }
}

3. Keep Checks Fast

Health checks should be fast (<1 second):

// ✅ Good - Fast ping
@HealthCheck()
protected async check() {
  return {
    connected: await this.redis.ping(),  // ~1-5ms
  };
}

// ❌ Bad - Slow query
@HealthCheck()
protected async check() {
  return {
    totalUsers: await this.db.users.count(),  // Could be slow!
  };
}

4. Return Useful Information

Include diagnostic information in your health checks:

@HealthCheck()
protected async check() {
  return {
    connected: true,
    latency: 5,               // ✅ Useful
    connections: {             // ✅ Useful
      active: 10,
      idle: 5,
      total: 15,
    },
    lastError: null,          // ✅ Useful
    version: this.getVersion(), // ✅ Useful
  };
}

Advanced Usage

Kubernetes Liveness/Readiness Probes

# kubernetes/deployment.yaml
spec:
  containers:
    - name: app
      livenessProbe:
        httpGet:
          path: /healthz
          port: 3000
        initialDelaySeconds: 10
        periodSeconds: 30
      readinessProbe:
        httpGet:
          path: /healthz
          port: 3000
        initialDelaySeconds: 5
        periodSeconds: 10

Custom Health Check Service

Inject HealthCheckService to programmatically check health:

import { Injectable } from '@nestjs/common';
import { HealthCheckService } from '@betternest/healthcheck';

@Injectable()
export class MonitoringService {
  constructor(
    private readonly healthCheck: HealthCheckService,
  ) {}

  async getApplicationHealth() {
    const health = await this.healthCheck.getHealth();

    if (health.hasError) {
      await this.sendAlert('Application health degraded', health);
    }

    return health;
  }

  async checkSpecificService(serviceName: string) {
    return this.healthCheck.getHealth(serviceName);
  }
}

Comparison with @nestjs/terminus

| Feature | @betternest/healthcheck | @nestjs/terminus | |---------|------------------------|------------------| | Setup | ✅ Zero config | ⚠️ Manual setup required | | Auto-discovery | ✅ Yes | ❌ No | | API | ✅ Simple decorator | ⚠️ Verbose HealthCheckService | | Type-safety | ✅ Full | ✅ Full | | Built-in indicators | ❌ DIY | ✅ Many built-in | | Custom indicators | ✅ Easy | ✅ Possible |

When to use @betternest/healthcheck:

  • ✅ You want zero configuration
  • ✅ You want auto-discovery
  • ✅ You prefer decorators over imperative code
  • ✅ You have custom health check logic

When to use @nestjs/terminus:

  • ✅ You need built-in indicators (disk, memory, etc.)
  • ✅ You want battle-tested library
  • ✅ You need complex health check composition

Examples

See the examples directory for complete working examples.

Troubleshooting

Health check not discovered

  1. Ensure HealthCheckModule is imported
  2. Verify method is decorated with @HealthCheck()
  3. Check that the service is properly registered as a provider
  4. Check logs for "Health check registered: ServiceName"

Multiple health checks error

Each service can only have ONE @HealthCheck() method. Combine multiple checks into one method:

@HealthCheck()
protected async check() {
  return {
    database: await this.checkDatabase(),
    cache: await this.checkCache(),
    api: await this.checkApi(),
  };
}

Contributing

Contributions are welcome! Please see CONTRIBUTING.md.

License

MIT © Mathieu

Related Packages


Part of the BetterNest ecosystem - Production-proven patterns for NestJS applications.