express-request-id
express-request-id copied to clipboard
support for CommonJS module system
We have setup an express app with TypeScript, and target CommonJS modules (which is still the default in TypeScript). Consequenty, we don't have "type": "module"
in package.json. When we install a version => 2.0.0 of express-request-id, and start the app, it crashes with the following error:
/Users/hermangruber/IdeaProjects/express-example/dist/index.js:8
const express_request_id_1 = __importDefault(require("express-request-id"));
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/hermangruber/IdeaProjects/express-example/node_modules/express-request-id/index.js from /Users/hermangruber/IdeaProjects/express-example/dist/index.js not supported.
Instead change the require of /Users/hermangruber/IdeaProjects/express-example/node_modules/express-request-id/index.js in /Users/hermangruber/IdeaProjects/express-example/dist/index.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/hermangruber/IdeaProjects/express-example/dist/index.js:8:46) {
code: 'ERR_REQUIRE_ESM'
}
A minimal repro using the latest version of express-request-id
can be found here:
https://github.com/HermannGruber/express-example
BTW, we tried to work around the issue by converting our app in full to ES2020 modules, but it seems that the rest of the ecosystem is not yet fully migrated to ESM. For example, jest 29.5 has only experimental support for ESM: https://jestjs.io/docs/ecmascript-modules
I tried a workaround using import()
- the ESM error is gone, but it still didn't work. Code:
const app = express();
(async () => {
const requestId = (await import("express-request-id")).default;
console.log(requestId); // Output: [Function: requestID]
app.use(requestId());
})();
app.get("/", function (req, res, next) {
res.send(req.id || res.id || "No id"); // Result: both are undefined, I get 'No id'
});
This helped - https://adamcoster.com/blog/commonjs-and-esm-importexport-compatibility-examples#how-to-import-commonjs-cjs-into-esm
Faced the same issue.
Thankfully, the logic is quite small and contained, which allowed me to copy the code over to a local file and import it that way.
import {v4 as uuidv4} from 'uuid';
import {Request, Response, NextFunction} from 'express';
function generateV4UUID(_request: any) {
return uuidv4();
}
const ATTRIBUTE_NAME = 'id';
export default function requestID({
generator = generateV4UUID,
headerName = 'X-Request-Id',
setHeader = true,
} = {}) {
return function (request: Request, response: Response, next: NextFunction) {
const oldValue = request.get(headerName);
const id = oldValue === undefined ? generator(request) : oldValue;
if (setHeader) {
response.set(headerName, id);
}
request[ATTRIBUTE_NAME] = id;
next();
};
}