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

@asp2025/middleware

v1.0.2

Published

Express middleware package for authentication, error handling, and logging

Readme

@asp2025/middleware

Express middleware package for authentication, error handling, and logging.

Installation

npm install @asp2025/middleware

Features

  • Authentication: JWT-based authentication middleware with role-based access control
  • Error Handling: Centralized error handling with custom error classes
  • Logging: Request/response logging middleware
  • Audit Logging: Send audit events to AWS SQS queue

Usage

Authentication Middleware

import express from "express";
import { authHandler, AuthenticatedRequest } from "@asp2025/middleware";

const app = express();

// Protect routes with JWT authentication
app.get("/api/admin", authHandler("admin"), (req, res) => {
  const { userId } = (req as AuthenticatedRequest).payload;
  res.json({ message: "Admin access", userId });
});

// Allow multiple roles
app.get("/api/users", authHandler("admin", "member"), (req, res) => {
  res.json({ message: "User access" });
});

Error Handling

import { 
  errorHandler, 
  NotFoundError, 
  ValidationError,
  UnauthorizedError 
} from "@asp2025/middleware";

// Use custom errors in your routes
app.get("/api/resource/:id", async (req, res, next) => {
  try {
    const resource = await findResource(req.params.id);
    if (!resource) {
      throw new NotFoundError("Resource not found");
    }
    res.json(resource);
  } catch (error) {
    next(error);
  }
});

// Add error handler as last middleware
app.use(errorHandler);

Logging Middleware

import { loggingHandler, Logger } from "@asp2025/middleware";
import winston from "winston";

// Create a logger that implements the Logger interface
const logger: Logger = {
  info: (msg) => winston.info(msg),
  warn: (msg) => winston.warn(msg),
  error: (msg) => winston.error(msg),
};

// Add logging middleware
app.use(loggingHandler(logger));

Audit Handler

import { auditHandler, ActionType } from "@asp2025/middleware";

// Send audit events to SQS
await auditHandler("[email protected]", {
  type: "LOGIN" as ActionType,
  description: "User logged into the system"
});

API Reference

Authentication

authHandler(...allowedRoles: UserRole[])

Creates authentication middleware that validates JWT tokens and checks user roles.

  • Parameters: allowedRoles - Array of allowed roles ("admin" | "member")
  • Returns: Express middleware function
  • Requires: JWT_SECRET environment variable

AuthenticatedRequest<P>

Extended Express Request interface with authenticated user payload.

interface AuthenticatedRequest<P = object> extends Request<P> {
  payload: JWTPayload;
}

JWTPayload

interface JWTPayload {
  userId: string;
  businessId: string | null;
  role: string;
  email: string;
}

Error Classes

All error classes extend BaseError:

  • ValidationError (400) - Validation errors
  • UnauthorizedError (403) - Authorization errors
  • ForbiddenError (403) - Access forbidden
  • NotFoundError (404) - Resource not found
  • ConflictError (409) - Conflict errors
  • ServiceUnavailableError (503) - Service unavailable

Usage:

import { NotFoundError } from "@asp2025/middleware";

throw new NotFoundError("Custom error message");

Error Handler

errorHandler(error, req, res, next)

Centralized error handling middleware that:

  • Handles Zod validation errors
  • Handles custom BaseError instances
  • Catches all other errors with 500 status

Logging

Logger Interface

interface Logger {
  info: (msg: string | object) => void;
  warn: (msg: string | object) => void;
  error: (msg: string | object) => void;
}

loggingHandler(logger: Logger)

Creates logging middleware that logs:

  • Request method, path, status code
  • Response time in milliseconds
  • User information (from JWT payload)
  • IP address

Audit

auditHandler(userEmail: string, action: AuditAction): Promise<void>

Sends audit events to an AWS SQS queue.

  • Parameters:
    • userEmail: Email of the user performing the action
    • action: Object with type (ActionType) and description
  • Returns: Promise that resolves when the message is sent
  • Requires: AWS_SQS_URL environment variable

ActionType

Union type of all supported audit action types:

type ActionType =
  | "CREATE_COMPANY"
  | "UPDATE_COMPANY"
  | "DELETE_COMPANY"
  | "INVITE_USER"
  | "REGISTER_USER"
  | "DELETE_USER"
  | "CREATE_TEAM"
  | "UPDATE_TEAM"
  | "DELETE_TEAM"
  | "CREATE_API_KEY"
  | "REVOKE_API_KEY"
  | "CREATE_DEAL"
  | "UPDATE_DEAL"
  | "DELETE_DEAL"
  | "CHANGE_DEAL_STAGE"
  | "UPLOAD_ATTACHMENT"
  | "DELETE_ATTACHMENT"
  | "SUBSCRIBE_NOTIFICATIONS"
  | "UNSUBSCRIBE_NOTIFICATIONS";

AuditAction

interface AuditAction {
  type: ActionType;
  description: string;
}

AuditEvent

interface AuditEvent {
  event_id: string;
  timestamp: string;
  user_email: string;
  action: AuditAction;
}

Environment Variables

Authentication

  • JWT_SECRET - Secret key for JWT token verification (required for authHandler)

Audit Logging

  • AWS_SQS_URL - SQS queue URL for audit events (required for auditHandler)
  • AWS_REGION - AWS region (optional, defaults to us-east-1)
  • AWS_ENDPOINT_URL - Custom SQS endpoint (optional, for LocalStack development)

Note: AWS credentials and region are handled by the AWS SDK's default credential chain. Set AWS_REGION if using a region other than us-east-1, or AWS_ENDPOINT_URL for LocalStack development.