In order to enhance the Express Request interface with a new property called "context" for middleware purposes, I am trying to achieve the following:
const myMiddleware = (req: Request, res: Response, next: NextFunction) => {
req.context.something = 'something'
next()
}
Currently, the error message displays:
Property 'context' does not exist on type 'Request'.
To resolve this issue, I attempted declaration merging by creating a custom.d.ts file as follows:
export {}
declare global {
namespace Express {
interface Request {
context?: any
}
}
}
I included export {}
in the file to prevent an error, but the context
property remains elusive.
Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.
Despite researching multiple solutions, extending the Request interface seems undesirable, and modifying the tsconfig.json with typeRoots
or files
properties did not yield positive results.
An additional suggestion involved using the express-serve-static-core
module which also proved ineffective:
declare module 'express-serve-static-core' {
interface Request {
context?: any
}
}
Despite numerous attempts based on similar questions, none of the proposed solutions seem to work in my case, leading me to believe that I might be missing a crucial step.
My project structure is as follows:
tsconfig.json
src/
custom.d.ts
some_folder/
some_file_that_needs_req.context
And here is my current tsconfig.json configuration:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"allowJs": true
}
}