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

nestjs-cloudwatch-metrics

v0.0.1

Published

NestJS CloudWatch Metrics

Readme

NestJS CloudWatch Metrics

A NestJS module for easy integration with AWS CloudWatch Metrics. This module provides a simple way to create, publish, and manage custom metrics for your application.

Installation

To install the module, you can use pnpm (or your preferred package manager):

pnpm add nestjs-cloudwatch-metrics

Usage

1. Import and Configure the Module

Import CloudwatchMetricsModule into your application module (e.g., app.module.ts) and configure it using the .forRoot() or .forRootAsync() static methods. You'll need to provide your AWS region and, optionally, your AWS credentials and default metric options.

// app.module.ts
import { Module } from "@nestjs/common";
import { CloudwatchMetricsModule } from "nestjs-cloudwatch-metrics";

@Module({
  imports: [
    CloudwatchMetricsModule.forRoot({
      region: "your-aws-region", // e.g., "us-east-1"
      // Optional: AWS credentials (if not configured elsewhere, e.g., via IAM roles)
      // accessKeyId: "YOUR_AWS_ACCESS_KEY_ID",
      // secretAccessKey: "YOUR_AWS_SECRET_ACCESS_KEY",
      // Optional: Default options for all metrics created by the service
      defaultMetricOptions: {
        sendInterval: 10000, // Send metrics every 10 seconds
        maxCapacity: 20, // Max metrics to store before sending
        // ... other MetricOptions
      },
    }),
    // ... other modules
  ],
})
export class AppModule {}

2. Inject the Service and Use Metrics

Inject CloudwatchMetricsService into your services or controllers where you want to publish metrics.

// my-service.service.ts
import { Injectable } from "@nestjs/common";
import {
  CloudwatchMetricsService,
  Metric,
  StandardUnit,
} from "nestjs-cloudwatch-metrics";

// Adjust path if using locally

@Injectable()
export class MyService {
  private readonly requestCounterMetric: Metric;

  constructor(private readonly cloudwatchService: CloudwatchMetricsService) {
    // Create a metric instance
    this.requestCounterMetric = this.cloudwatchService.createMetric(
      "MyApplicationNamespace", // Your CloudWatch Namespace
      StandardUnit.Count, // The unit for this metric
      [
        { Name: "Environment", Value: "Production" }, // Default dimensions for this metric
      ],
      {
        // Metric-specific options (overrides defaultMetricOptions)
        sendInterval: 5000, // Send this specific metric every 5 seconds
      },
    );
  }

  handleRequest() {
    // ... your request handling logic ...

    // Publish a metric datapoint
    this.requestCounterMetric.put(
      1, // The value of the metric
      "IncomingRequests", // The name of the metric
      [{ Name: "Route", Value: "/api/data" }], // Additional dimensions for this specific datapoint
    );
  }

  async processBatchJob(items: any[]) {
    // ... your batch job logic ...
    const batchSize = items.length;

    // Example of summarizing metric data over time
    // This is useful for things like processing time, where you want min/max/avg/sum/count
    this.requestCounterMetric.summaryPut(batchSize, "ProcessedBatchSize", [
      { Name: "JobType", Value: "NightlySync" },
    ]);

    // Example of sampling metric data (e.g., only send 10% of datapoints)
    this.requestCounterMetric.sample(
      batchSize,
      "SampledProcessedBatchSize",
      [{ Name: "JobType", Value: "NightlySync" }],
      0.1, // Sample rate: 10%
    );
  }
}

Metric Options

The following options can be provided when creating a metric or as default options for the module:

  • enabled: boolean (default: true) - Whether the metric is enabled and should send data.
  • sendInterval: number (default: 5000 ms) - Interval in milliseconds to send batched metrics.
  • summaryInterval: number (default: 10000 ms) - Interval in milliseconds to send summarized metrics.
  • sendCallback: (err?: Error) => void (default: () => {}) - Callback function executed after metrics are sent.
  • maxCapacity: number (default: 20) - Maximum number of metric data points to store before sending immediately.
  • withTimestamp: boolean (default: false) - Whether to include a Timestamp with each metric data point.
  • storageResolution: number (default: undefined) - The resolution, in seconds, for the metric. Valid values are 1 and 60.

Available Methods on Metric instances

  • put(value: number, metricName: string, additionalDimensions?: Dimension[]): void
    • Publishes a single metric data point.
  • summaryPut(value: number, metricName: string, additionalDimensions?: Dimension[]): void
    • Adds a data point to a summary set (sends min, max, sum, count, avg at summaryInterval).
  • sample(value: number, metricName: string, additionalDimensions?: Dimension[], sampleRate: number): void
    • Publishes a metric data point based on a sample rate (0.0 to 1.0).
  • shutdown(): void
    • Clears intervals and sends any pending metrics. Called automatically OnModuleDestroy for metrics created via the service.
  • hasMetrics(): boolean
    • Returns true if there are metrics pending to be sent.