@uocdev/apihelper
v1.2.0
Published
A lightweight and secure HTTP header manager for Express and Fastify APIs.
Maintainers
Readme
@uocdev/apihelper is a lightweight, modular, and secure HTTP header manager for Node.js APIs.
It works seamlessly with Express, Fastify, and other Node HTTP frameworks.
This package helps you apply secure HTTP headers out-of-the-box while keeping full flexibility.
Features
- Predefined secure headers for production, development, and testing
- Supports custom headers
- Middleware-friendly (Express/Fastify compatible)
- Optional console logging for debugging
- Fully written in TypeScript
- CORS: Enable/disable CORS, whitelist domains, preflight handling
- Content Security Policy (CSP): Generate secure headers from JSON rules
- Rate Limiting: Limit requests per IP with TTL, built-in middleware
- HSTS: Auto set HTTP Strict Transport Security for production
- Diagnostics & Monitoring (NEW in v1.2.0):
- Error Tracking: Centralized error handling middleware
- Health Check: Built-in health check endpoints with memory metrics
- Logger: Flexible request logging with multiple formats and outputs
- Metrics: Prometheus-compatible metrics endpoint
- Performance: Response time tracking with X-Response-Time header
Installation
npm install @uocdev/apihelpernpm install @uocdev/apihelper@latest #use "@" to other version or latestPackage Information
- Version: 1.2.0
- Owner Repository: UocDev
- License: MIT
- Programing Language: TypeScript / JavaScript
Example Usage
Normal operations
with Express
import express from "express";
import apihelper from "@uocdev/apihelper";
const app = express();
app.use(apihelper({
mode: "production",
log: true,
headers: {
"X-Powered-By": false,
"Content-Security-Policy": "default-src 'self'"
}
}));
app.get("/", (req, res) => res.send("Hello Express!"));
app.listen(3000, () => console.log("Server running on http://localhost:3000"));with Fastify
import Fastify from "fastify";
import apihelper from "@uocdev/apihelper";
const fastify = Fastify();
fastify.addHook("onSend", apihelper({
mode: "production",
log: true
}));
fastify.get("/", async () => "Hello Fastify!");
fastify.listen({ port: 3000 }, () => console.log("Server running on http://localhost:3000"));Note: For Fastify, we apply apihelper as an onSend hook to set headers.
with Node.js (Pure)
import http from "http";
import apihelper from "@uocdev/apihelper";
const headersMiddleware = apihelper({
mode: "production",
log: true
});
const server = http.createServer((req, res) => {
// fake express-like next
headersMiddleware(req, res, () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Node.js!");
});
});
server.listen(3000, () => console.log("Server running on http://localhost:3000"));Note: For pure Node.js is use HTTP and some feature must write long
With Security
With Express
import express from "express";
import apihelper from "@uocdev/apihelper";
const app = express();
app.use(apihelper({
mode: "production",
log: true,
security: {
cors: { enabled: true, origin: ["https://myapp.com"], methods: ["GET","POST"] },
csp: { "default-src": ["'self'"], "img-src": ["'self'","https://cdn.example.com"] },
rateLimit: { enabled: true, max: 100, ttl: 60 },
hsts: true
}
}));
app.get("/", (req, res) => res.send("Hello Express with Security!"));
app.listen(3000, () => console.log("Server running on http://localhost:3000"));With Fastify
import Fastify from "fastify";
import apihelper from "@uocdev/apihelper";
const fastify = Fastify();
fastify.addHook("onSend", apihelper({
security: {
cors: { enabled: true, origin: ["https://myapp.com"] },
csp: { "default-src": ["'self'"] },
hsts: true
}
}));
fastify.get("/", async () => "Hello Fastify with Security!");
fastify.listen({ port: 3000 }, () => console.log("Server running on http://localhost:3000"));With Node.js
import http from "http";
import apihelper from "@uocdev/apihelper";
const headersMiddleware = apihelper({
security: {
cors: { enabled: true, origin: "*" },
csp: { "default-src": ["'self'"] },
hsts: true
}
});
const server = http.createServer((req, res) => {
headersMiddleware(req, res, () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Node.js with Security!");
});
});
server.listen(3000, () => console.log("Server running on http://localhost:3000"));API
normal API
apihelper(options?: {
mode?: "production" | "development" | "testing"; // default: production
headers?: Record<string, string | boolean>; // override or add headers
log?: boolean; // log applied headers
}): (req, res, next) => voidSecurity API
security?: {
cors?: {
enabled?: boolean;
origin?: string[] | "*";
methods?: string[];
};
csp?: Record<string, string[]>;
rateLimit?: {
enabled?: boolean;
max?: number;
ttl?: number; // seconds
};
hsts?: boolean;
}Presets
production: Recommended security headers for live servers
development: Less strict headers for debugging
testing: Custom headers for testing environments
Security
CORS:
OPTIONSpreflight requests are automatically handled and returned with status204.Rate Limiting: IP-based; request exceeding limit will respond
429with "Rate limit exceeded".HSTS: Only applied when
hsts: trueis set.CSP: JSON rules automatically converted to
Content-Security-Policyheader.
Diagnostics & Monitoring (v1.2.0)
The new diagnostics module provides powerful monitoring and debugging tools for your API.
Error Tracking
Centralized error handling middleware:
import express from "express";
import apihelper from "@uocdev/apihelper";
import { errorTracking } from "@uocdev/apihelper";
const app = express();
app.use(apihelper({ mode: "production" }));
app.get("/error", () => {
throw new Error("Test error");
});
// Apply error tracking middleware (must be last)
app.use(errorTracking());
app.listen(3000);Health Check
Add health check endpoints to monitor application status:
import express from "express";
import { healthCheck } from "@uocdev/apihelper";
const app = express();
// Adds GET /__health endpoint
healthCheck(app);
// Or custom path
healthCheck(app, "/api/health");
app.listen(3000);
// GET /__health returns: { status: "ok", uptime: 123.45, memory: { rss: ..., heapUsed: ... } }Logger
Flexible request logging with multiple formats:
import express from "express";
import { logger } from "@uocdev/apihelper";
const app = express();
// Development format (default)
app.use(logger({ format: "dev" }));
// Output: GET /api/users 200 - 15.23ms
// JSON format
app.use(logger({ format: "json" }));
// Output: {"method":"GET","url":"/api/users","status":200,"duration":"15.23ms","time":"2025-11-04T12:00:00.000Z"}
// Tiny format
app.use(logger({ format: "tiny" }));
// Output: GET /api/users 200
// Log to file
app.use(logger({ output: "file", filePath: "./logs/access.log" }));
// Custom output handler
app.use(logger({
output: (msg) => {
// Send to external logging service
console.log(msg);
}
}));
app.listen(3000);Metrics
Prometheus-compatible metrics endpoint:
import express from "express";
import { metrics } from "@uocdev/apihelper";
const app = express();
// Adds GET /__metrics endpoint
metrics(app);
// Or custom path
metrics(app, "/api/metrics");
app.listen(3000);
// GET /__metrics returns Prometheus-style metricsPerformance Monitoring
Track response times automatically:
import express from "express";
import { performance } from "@uocdev/apihelper";
const app = express();
// Adds X-Response-Time header to all responses
app.use(performance());
app.get("/", (req, res) => res.send("Hello!"));
// Response includes: X-Response-Time: 5.23ms
app.listen(3000);Complete Diagnostics Example
import express from "express";
import apihelper from "@uocdev/apihelper";
import { errorTracking } from "@uocdev/apihelper";
import { healthCheck } from "@uocdev/apihelper";
import { logger } from "@uocdev/apihelper";
import { metrics } from "@uocdev/apihelper";
import { performance } from "@uocdev/apihelper";
const app = express();
// Security headers
app.use(apihelper({ mode: "production" }));
// Diagnostics middleware
app.use(logger({ format: "dev" }));
app.use(performance());
// Health & metrics endpoints
healthCheck(app);
metrics(app);
// Your routes
app.get("/", (req, res) => res.send("Hello!"));
// Error tracking (must be last)
app.use(errorTracking());
app.listen(3000, () => console.log("Server running with full diagnostics"));License
This package NPM completely free and open source under MIT License. we're welcoming you to open Pull Request to add new features and open Issue Request for helping this package better time to time.
