I have a middleware and it returns an object back. I need to store this object so that the rest of the application can use the data from that object. How do I do it?
This is what I have in my app.js file:
import { myMiddlewareFunction } from "@mymiddleware"
app.use(async function (req, res, next) {
try {
const params = {...someparams};
const response: MyMiddlewareResponse = await myMiddlewareFunction (
req,
params
);
if (!response.isValid) {
res.send("401: Not Valid");
return;
}
next();
} catch (err) {
next(err);
}
});
The response interface looks like this:
interface MyMiddlewareResponse {
isValid: boolean;
store_id: number;
salesManInfo?: SalesMan;
}
I want the response
object to be available to the rest of my application so that it can access response.store_id
and response.salesManInfo
for business logic.
Some really old posts here said that I can tag the value to req
object.
So, I tried req.mymiddlewarerespose=response
but that threw an error Property 'mymiddlewarerespose' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
.
TIA
2
Answers
If you really want to store this data GLOBALLY for the entire server (and for all requests and all users), then you can put the data into a property on the
app
object or as a module-level variable or (heaven-forbid) as an actual global variable.But, "Rest of the application can use that" is a usually a dangerous way to say things. This is one request from one user. A server typically handles many requests from many different users and one user’s data should not ever be able to get confused with data from another user.
So, usually, you are handling data only on behalf of a specific user. To do that with server middleware, you have two main options:
Add the data to the user’s session object (using something like express-session) where it will persist as long as the user’s session persists (which you control). This data will then be available for any requests being processed from that user in the future.
Add the data as a property on the current
req
object so that the rest of the request handling code can then access that data (this is a classic job of middleware, preparing data to be used later in this particular request handling). In this case, the data will only be available for the rest of the processing of this request. Once this request is over, the data will no longer be accessible.you can do it something like this –
update –