postgresqljwtrefresh-tokennext.js14

JWT: Refresh token and access token storage


There are many posts about JWT but none have seemed to solve my confusion.

In my current project (Next.js 14 and Postgres) I am attempting to create my own authentication to learn more about important concepts.

Currently, when a user logs in, an access token gets stored in the cookies (HTTP only). I have middleware that checks for the validity of this token, but when this token is not valid or expired, I want my middleware to call an api to retrieve a new access token with a refresh token.

Do I store this refresh token in the cookies also or is it possible to store in my postgres db?

Because if I want my middleware to call an api to get a new access token, I grab the refresh token and check the validity of it then get a new access token.

I don't know how to implement it with the postgres db because I don't understand how the server can know what users' refresh token to grab from the table.

So really my question is, is it okay just to store the refresh token with the access token? If not, how can I implement the database logic, because I have heard it's good to have the refresh token stored in the server.


Solution

  • I think your question is a bit unclear what is executed client side and what is executed server side. I will make some assumptions.

    First of all, the client must store both your access token and your refresh token, and both must be sotred securely on the client side. See https://stackoverflow.com/a/76889949/2889165

    You have a few different options for how to store the refresh token client side. I have seen the following:

    Secondly the refresh token can either be self sustained, like being a signed JWT used in a stateless backend, or the refresh token can be stored both client side and server side for a stateful backend.