I discussed a question with many people and the question was - Do you store the JWT tokens in the database?
First Answer: Yes, we do store. Whenever we got an API call we get the token from the header and match it with the tokens that we have stored in DB.
Second Answer: No, we don't store tokens in a database we simply get them verified by JWT itself. We get the token from the header and pass it JWT verify method like jwt.verify(token, secret).
What I feel is that it is not required to store the tokens in the database. Because if you will be storing tokens in the database then you'll be setting some TTL(expiry time) there and on every request you will be verifying the token with user requested token and every time you'll update the TTL.
Let say my token TTL is 30 minutes, I logged into the app and made a second API call after 5 minutes, in that case, you will be first verifying my token and then updating my TTL back to 30 minutes. Seems a little costly right???
Solution: What I can do is, I can store the list of blocked tokens and you can verify tokens using jwt.verify(token, secret).
Let say, I have created a list of blocked tokens where TTL is set to 30 minutes. Whenever the user will log out, I'll store that user token into my database with a TTL of 30 minutes. If you try to make the API call with the same token after 5 minutes of log out, I'll verify the token using jwt.verify(token, secret) and it will be returning true because the token is valid for the next 25 minutes also. Then I'll also verify that the token in the blocked list and it should not exist in the blocked list. So in this case user token will be found in the blocked list then I'll not allow the user to access the API.
So this way will be saving 1 DB query of updating the TTL every time and I believe that number of tokens will be less in the blocked list in comparison to the list of tokens of all the logged-in users. So finding the token in the small list(blocked tokens) will be faster.
JWT doesn't maintain a list of tokens or logged-out tokens so that it can verify the tokens of logged-out users. It simply verifies the token is valid or not based on secret and expiry time.
We also can generate the new token on every request and return it in the response, the application which is consuming API will send that new token in the next request, and the cycle repeats.