Exframe Common Middleware
raw JSON →The `exframe-middleware` package, currently at version 1.5.5, offers a centralized collection of commonly used middleware functions tailored for both Express.js applications and RabbitMQ RPC services within the broader Exframe ecosystem. Its primary goal is to standardize cross-cutting concerns, such as robust error handling, user authorization, Content Security Policy (CSP) construction, request context building, and consistent API response formatting. Unlike general-purpose middleware libraries, `exframe-middleware` provides specific utilities like `authorizeUser` and `buildExpressRequestContext`, which are designed to integrate seamlessly into an existing Exframe-based microservice architecture. It explicitly uses CommonJS `require()` in its documentation, indicating it was developed with a CJS-first approach. The library promotes consistency and reduces boilerplate across services that require similar operational patterns. Release cadence is not explicitly stated but appears to be stable, with infrequent updates typical for foundational utilities.
Common errors
error ReferenceError: require is not defined in ES module scope ↓
"type": "module" from package.json and using .js extensions, or dynamically import() the module if no native ESM entry point is available, e.g., const { handleErrors } = await import('exframe-middleware');. error TypeError: handleErrors is not a function ↓
handleErrors is called as a function to return the object containing the specific middleware. Correct usage is app.use(handleErrors().express);. error UnauthorizedError: User not found ↓
req.user) *before* the authorizeUser middleware in your Express route chain. Warnings
gotcha The library is primarily a CommonJS module, with examples explicitly using `require()`. Direct `import` statements in an ES module context may lead to runtime errors (e.g., `ERR_REQUIRE_ESM`) if a default export or 'exports' map is not configured for ESM compatibility. Projects should primarily use `require()`. ↓
breaking The package explicitly declares `engines.node: >=14.0.0`. Running on older Node.js versions might lead to unexpected behavior or runtime errors due to reliance on newer language features or APIs. ↓
gotcha The `authorizeUser` middleware expects a `user` object to be present on the `request` object (e.g., `req.user`). This implies a preceding authentication middleware (not provided by this package) is responsible for populating `req.user` prior to `authorizeUser` being invoked, otherwise it will always throw an `UnauthorizedError`. ↓
Install
npm install exframe-middleware yarn add exframe-middleware pnpm add exframe-middleware Imports
- handleErrors wrong
const handleErrors = require('exframe-middleware').handleErrors;correctimport { handleErrors } from 'exframe-middleware'; - authorizeUser wrong
const authorizeUser = require('exframe-middleware');correctimport { authorizeUser } from 'exframe-middleware'; - standardRouteResponseBuilder wrong
const { default: standardRouteResponseBuilder } = require('exframe-middleware');correctimport { standardRouteResponseBuilder } from 'exframe-middleware';
Quickstart
const express = require('express');
const { handleErrors, authorizeUser } = require('exframe-middleware');
const app = express();
const port = process.env.PORT || 3000;
// Apply global error handling middleware
app.use(handleErrors().express);
// Example route with user authorization
app.get('/protected', authorizeUser, (req, res) => {
// In a real app, 'req.user' would be populated by a preceding auth middleware.
// For this example, we'll simulate a user if one isn't set for authorizeUser to pass.
if (!req.user) {
req.user = { id: 'test-user', roles: ['admin'] };
}
res.json({ message: 'Access granted to protected resource!', user: req.user });
});
// Basic unprotected route
app.get('/', (req, res) => {
res.send('Hello from Exframe Middleware example!');
});
// Simulate an error to be caught by handleErrors
app.get('/error', (req, res, next) => {
next(new Error('Something went wrong on purpose!'));
});
// If no preceding auth middleware populates req.user, this route will throw UnauthorizedError
app.get('/always-fail-auth', authorizeUser, (req, res) => {
res.send('This should not be reached.');
});
app.listen(port, () => {
console.log(`Exframe Middleware Express app listening on http://localhost:${port}`);
});