Shared Express middleware for Swoft microservices
npm install @swoft/middlewareShared Express middleware for Swoft microservices. Provides consistent behavior across all backend services.
``bash`
pnpm add @swoft/middleware
Adds standardized metadata to all JSON responses for debugging, tracing, and monitoring.
`typescript
import express from 'express';
import { createResponseMetadataMiddleware } from '@swoft/middleware';
const app = express();
app.use(
createResponseMetadataMiddleware({
serviceName: 'my-service',
version: '1.0.0',
})
);
`
`typescript`
app.use(
createResponseMetadataMiddleware({
serviceName: '@swoft/collaboration-backend',
version: '2.0.0',
includeDatabase: true,
databaseType: 'mongodb',
getDatabaseStatus: () => db.isConnected(),
getPort: () => parseInt(process.env.PORT || '4004'),
enableRequestIdHeader: true,
})
);
All responses will be wrapped with metadata:
`json`
{
"data": {
/ original response /
},
"metadata": {
"service": "@swoft/collaboration-backend",
"environment": "development",
"database": {
"type": "mongodb",
"url": "mongodb://localhost:27017/swoft",
"connected": true
},
"server": {
"hostname": "dev-machine",
"port": 4004,
"pid": 12345
},
"timestamp": "2025-01-25T16:30:00.000Z",
"version": "2.0.0",
"responseTimeMs": 45,
"requestId": "1753460000000-abc123def"
}
}
For MCP tools that call backend services:
`typescript
import { addMCPMetadata, extractMetadata } from '@swoft/middleware';
// In your MCP tool
const backendResponse = await fetch('/api/gtd/tasks');
const responseWithMCPMetadata = addMCPMetadata(backendResponse, {
tool: 'gtd_project_list',
version: '1.0.0',
processingTimeMs: 5,
});
`
In production (NODE_ENV=production):
- Database information is hidden
- Server hostname and PID are masked
- Less sensitive metadata is included
- NODE_ENV - Controls production mode behaviorAPI_VERSION
- - Default version if not specifiedPORT
- - Default port if getPort not providedMONGODB_URI
- - Database connection string (password sanitized)
This package will grow to include:
- Error handling middleware
- Request validation middleware
- Rate limiting middleware
- Authentication middleware
- CORS configuration
When adding new middleware:
1. Create a new directory under src/src/index.ts`
2. Export from
3. Add documentation to this README
4. Include TypeScript types