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

zeratus-api

v1.0.1

Published

A powerful, production-ready Fastify boilerplate library built by Zeratus for rapid API development

Readme

Zeratus API

A powerful, production-ready Fastify boilerplate library built by Zeratus for rapid API development. This library provides a comprehensive set of tools and abstractions for building scalable, maintainable APIs with TypeScript.

🚀 Features

  • 🔥 Fastify-based: Built on top of the fastest Node.js web framework
  • 📝 TypeScript First: Full TypeScript support with comprehensive type definitions
  • 🔌 Modular Architecture: Clean separation of concerns with pluggable components
  • 📊 Built-in Monitoring: Integrated logging, metrics, and error reporting
  • 🔄 Queue Management: RabbitMQ integration for background job processing
  • 💾 Caching Layer: Redis integration with advanced caching strategies
  • 🔐 Security: Built-in rate limiting, CORS, and security headers
  • 🌐 Real-time: Socket.IO integration for WebSocket communication
  • 🗄️ Database: Prisma integration for type-safe database operations
  • 📈 Observability: Sentry integration for error tracking and performance monitoring

📦 Installation

npm install zeratus-api

🏗️ Quick Start

import { Api } from "zeratus-api";

const api = new Api({
  logger: {
    format: { timestamp: true, requestId: true },
  },
  database: {
    url: process.env.DATABASE_URL,
  },
  cache: {
    url: process.env.REDIS_URL,
    keyPrefix: "myapp",
    defaultTTL: 3600,
  },
  errorReporter: {
    dsn: process.env.SENTRY_DSN,
    environment: process.env.NODE_ENV,
  },
});

// Register your routes
api.registerRoutes((app) => {
  app.get("/health", async (request, reply) => {
    return { status: "OK", timestamp: Date.now() };
  });

  app.get("/users/:id", async (request, reply) => {
    const { id } = request.params;
    const user = await api.database?.findUnique("user", { id });
    return user;
  });
});

// Initialize and start
async function start() {
  await api.initialize();
  await api.start(3000);
}

start().catch(console.error);

🔧 Configuration

Complete Configuration Example

import { Api } from "zeratus-api";

const api = new Api({
  // Logging configuration
  logger: {
    format: {
      timestamp: true,
      requestId: true,
      environment: true,
    },
    redactFields: ["password", "token", "authorization"],
    requestTracking: {
      headers: { enabled: true, fields: ["user-agent", "x-forwarded-for"] },
      body: { enabled: true, maxDepth: 2 },
      query: { enabled: true },
    },
    timing: {
      slow_threshold: 1000,
      include_db_time: true,
    },
  },

  // Database configuration
  database: {
    url: process.env.DATABASE_URL,
  },

  // Cache configuration
  cache: {
    url: process.env.REDIS_URL,
    keyPrefix: "myapp",
    keyDelimiter: ":",
    defaultTTL: 3600,
    ttlByPattern: {
      "user:*": 1800,
      "session:*": 900,
    },
    batchSize: 100,
  },

  // Queue configuration
  queues: {
    configs: [
      {
        url: process.env.RABBITMQ_URL,
        name: "email-queue",
        prefetchCount: 10,
      },
      {
        url: process.env.RABBITMQ_URL,
        name: "notification-queue",
        prefetchCount: 5,
      },
    ],
  },

  // Socket.IO configuration
  socket: {
    cors: {
      origin: process.env.CORS_ORIGIN || "*",
      methods: ["GET", "POST"],
      credentials: true,
    },
    transports: ["websocket", "polling"],
    pingTimeout: 20000,
    pingInterval: 25000,
  },

  // Error reporting configuration
  errorReporter: {
    dsn: process.env.SENTRY_DSN,
    environment: process.env.NODE_ENV,
    release: process.env.APP_VERSION,
    errorTypes: {
      VALIDATION_ERROR: "Validation Error",
      AUTH_ERROR: "Authentication Error",
      RATE_LIMIT_ERROR: "Rate Limit Exceeded",
      NOT_FOUND_ERROR: "Resource Not Found",
      SERVER_ERROR: "Internal Server Error",
    },
    responseFormat: {
      includeStack: process.env.NODE_ENV !== "production",
      includeErrorCode: true,
      includeTimestamp: true,
    },
  },

  // Rate limiting configuration
  rateLimit: {
    defaultLimit: 100,
    windowMs: 60000, // 1 minute
    routeLimits: {
      "/api/auth/login": { limit: 5, windowMs: 60000 },
      "/api/users": { limit: 50, windowMs: 60000 },
    },
    storage: {
      type: "redis",
      prefix: "rate-limit",
      ttl: 60,
    },
  },

  // Fastify server configuration
  fastify: {
    bodyLimit: 1048576, // 1MB
    connectionTimeout: 30000,
    keepAliveTimeout: 5000,
  },
});

🏛️ Architecture

Core Components

  • Api: Main application class that orchestrates all components
  • Logger: Structured logging with Pino
  • Database: Type-safe database operations with Prisma
  • Cache: Redis-based caching with advanced features
  • Queue: RabbitMQ integration for background jobs
  • Socket: Real-time communication with Socket.IO
  • ErrorReporter: Error tracking and monitoring with Sentry

Component Usage

Database Operations

// Create
const user = await api.database?.create("user", {
  email: "[email protected]",
  name: "John Doe",
});

// Find
const user = await api.database?.findUnique("user", { id: "123" });
const users = await api.database?.findMany("user", {
  where: { active: true },
  take: 10,
  skip: 0,
});

// Update
const updatedUser = await api.database?.update(
  "user",
  { id: "123" },
  { name: "Jane Doe" }
);

// Transactions
await api.database?.transaction(async (tx) => {
  await tx.create("user", userData);
  await tx.create("profile", profileData);
});

Caching

// Basic operations
await api.cache?.set("user:123", JSON.stringify(user), { ttl: 3600 });
const cachedUser = await api.cache?.get("user:123");
await api.cache?.del("user:123");

// Hash operations
await api.cache?.hset("user:123", "name", "John Doe");
const name = await api.cache?.hget("user:123", "name");

// Pub/Sub
await api.cache?.subscribe("notifications", (message) => {
  console.log("Received:", message);
});
await api.cache?.publish("notifications", "Hello World");

Queue Management

const emailQueue = api.getQueue("email-queue");

// Publish messages
await emailQueue?.publish(
  "email.send",
  "",
  Buffer.from(
    JSON.stringify({
      to: "[email protected]",
      subject: "Welcome!",
      body: "Welcome to our platform!",
    })
  )
);

// Consume messages
await emailQueue?.consume("email.send", async (msg) => {
  if (msg) {
    const data = JSON.parse(msg.content.toString());
    await sendEmail(data);
    emailQueue.ack(msg);
  }
});

Real-time Communication

// Emit to all clients
api.socket?.emit("notification", { message: "Hello everyone!" });

// Handle connections
api.socket?.onConnection((socket) => {
  console.log("Client connected:", socket.id);

  socket.on("message", (data) => {
    console.log("Received:", data);
  });
});

🛠️ Development Tools

Dependency Analysis

Check for unused dependencies in your project:

npm run check-unused-deps

This will analyze your codebase and identify potentially unused dependencies, helping keep your bundle size optimized.

🔒 Security Features

  • Rate Limiting: Configurable rate limiting per route or globally
  • CORS: Cross-Origin Resource Sharing configuration
  • Security Headers: Helmet integration for security headers
  • Input Validation: Built-in request validation capabilities
  • Error Sanitization: Automatic error message sanitization in production

📊 Monitoring & Observability

  • Structured Logging: JSON-formatted logs with correlation IDs
  • Request Tracking: Automatic request/response logging with timing
  • Health Checks: Built-in health check endpoints
  • Metrics: Prometheus-compatible metrics endpoint
  • Error Reporting: Automatic error reporting to Sentry
  • Performance Monitoring: Request timing and slow query detection

🚀 Production Deployment

Environment Variables

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/db

# Cache
REDIS_URL=redis://localhost:6379

# Queue
RABBITMQ_URL=amqp://localhost:5672

# Error Reporting
SENTRY_DSN=https://your-sentry-dsn

# Application
NODE_ENV=production
PORT=3000
CORS_ORIGIN=https://yourdomain.com

Docker Example

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3000

CMD ["node", "dist/index.js"]

🤝 Contributing

This library is maintained by Zeratus. For internal development:

  1. Clone the repository
  2. Install dependencies: npm install
  3. Build the project: npm run build
  4. Run dependency analysis: npm run check-unused-deps

📄 License

Private - Zeratus Internal Use

🏢 About Zeratus

Zeratus is a technology company focused on building scalable, maintainable software solutions. This API boilerplate represents our best practices and patterns for Node.js API development.


Built with ❤️ by the Zeratus Team