{"id":17601,"library":"exframe-middleware","title":"Exframe Common Middleware","description":"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.","status":"active","version":"1.5.5","language":"javascript","source_language":"en","source_url":null,"tags":["javascript"],"install":[{"cmd":"npm install exframe-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add exframe-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add exframe-middleware","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package documentation primarily uses CommonJS `require()`. While ESM import syntax may work via bundlers or Node.js's ESM interop, native ESM support is not explicitly guaranteed without a package 'exports' map. `handleErrors` is a function that returns an object containing `express` and `mq` middleware.","wrong":"const handleErrors = require('exframe-middleware').handleErrors;","symbol":"handleErrors","correct":"import { handleErrors } from 'exframe-middleware';"},{"note":"`authorizeUser` is a named export. Ensure it's imported correctly. It expects `req.user` to be populated by preceding middleware.","wrong":"const authorizeUser = require('exframe-middleware');","symbol":"authorizeUser","correct":"import { authorizeUser } from 'exframe-middleware';"},{"note":"`standardRouteResponseBuilder` is a named export, not a default export. It contains utility functions like `singleItem` for formatting responses.","wrong":"const { default: standardRouteResponseBuilder } = require('exframe-middleware');","symbol":"standardRouteResponseBuilder","correct":"import { standardRouteResponseBuilder } from 'exframe-middleware';"}],"quickstart":{"code":"const express = require('express');\nconst { handleErrors, authorizeUser } = require('exframe-middleware');\n\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Apply global error handling middleware\napp.use(handleErrors().express);\n\n// Example route with user authorization\napp.get('/protected', authorizeUser, (req, res) => {\n  // In a real app, 'req.user' would be populated by a preceding auth middleware.\n  // For this example, we'll simulate a user if one isn't set for authorizeUser to pass.\n  if (!req.user) {\n    req.user = { id: 'test-user', roles: ['admin'] };\n  }\n  res.json({ message: 'Access granted to protected resource!', user: req.user });\n});\n\n// Basic unprotected route\napp.get('/', (req, res) => {\n  res.send('Hello from Exframe Middleware example!');\n});\n\n// Simulate an error to be caught by handleErrors\napp.get('/error', (req, res, next) => {\n  next(new Error('Something went wrong on purpose!'));\n});\n\n// If no preceding auth middleware populates req.user, this route will throw UnauthorizedError\napp.get('/always-fail-auth', authorizeUser, (req, res) => {\n  res.send('This should not be reached.');\n});\n\napp.listen(port, () => {\n  console.log(`Exframe Middleware Express app listening on http://localhost:${port}`);\n});","lang":"javascript","description":"Demonstrates setting up `handleErrors` for Express and applying `authorizeUser` on a protected route, showcasing common middleware patterns within an Express application. It also shows a simulated error and a route demonstrating expected authorization failure."},"warnings":[{"fix":"Use `const { Name } = require('exframe-middleware');` for all imports. If in an ES module context, consider dynamic `import()` or transpilation.","message":"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()`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your Node.js runtime environment is version 14.0.0 or higher. Use a Node.js version manager like `nvm` to switch versions if necessary.","message":"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.","severity":"breaking","affected_versions":"<14.0.0"},{"fix":"Implement and apply an authentication middleware (e.g., using Passport.js or a custom solution) *before* `authorizeUser` to correctly populate `req.user` with authenticated user data.","message":"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`.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Either change your project to CommonJS by removing `\"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');`.","cause":"Attempting to use `require()` syntax in an ES module file (e.g., a `.mjs` file or a file where `\"type\": \"module\"` is set in `package.json`).","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Ensure `handleErrors` is called as a function to return the object containing the specific middleware. Correct usage is `app.use(handleErrors().express);`.","cause":"Attempting to use `handleErrors` directly as a middleware function or accessing its properties (like `.express`) without invoking it first.","error":"TypeError: handleErrors is not a function"},{"fix":"Implement and apply an authentication middleware (e.g., one that verifies a token and sets `req.user`) *before* the `authorizeUser` middleware in your Express route chain.","cause":"The `authorizeUser` middleware was invoked, but `req.user` was `undefined` or falsy, indicating no user object was populated by a preceding authentication layer.","error":"UnauthorizedError: User not found"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}