@asp2025/middleware
v1.0.2
Published
Express middleware package for authentication, error handling, and logging
Maintainers
Readme
@asp2025/middleware
Express middleware package for authentication, error handling, and logging.
Installation
npm install @asp2025/middlewareFeatures
- 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_SECRETenvironment 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 errorsUnauthorizedError(403) - Authorization errorsForbiddenError(403) - Access forbiddenNotFoundError(404) - Resource not foundConflictError(409) - Conflict errorsServiceUnavailableError(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 actionaction: Object withtype(ActionType) anddescription
- Returns: Promise that resolves when the message is sent
- Requires:
AWS_SQS_URLenvironment 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 tous-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.
