I'm building a backend with express js. Some endpoints are protected, so that only authenticated users can access there endpoints. Therefore i implemented a jwt token exchange.
Now what i want to do is creating a middelware for all protected endpoints which checks, if the request contains a token and validate this token if it is expired.
When the token is expired the middelware responses with a 401 status code.
When it's not expired the middelware checks if the token will expire soon. When it will be expire the middelware should create a new token and presets it in the response body, something like res.body = { newGeneratedToken }.
Then the endpoint the user called will be executed.
In this endpoint i will be able to add data to the response. Normaly i do this with res.json(myResponseData).
But i think this will overwrite the data i preseted in the middelware. So my newly created tokens will be overwritten.
Do you know how to implement this without doing the validating and creating stuff in each endpoint?
Thank you
Edit:
Is it a good idea to create a new token before the old one is expired? Maybe i should only use my "fallback" scenario when the token is already expired.