skip to Main Content

I’m practicing node js for server side of my app and react js for client side of my app, and I made my own auth server in node js to verify the refresh token and issue both of refresh and access tokens and authenticate user credentials too.

However, I don’t know how to refresh the access token using the refresh token in user’s cookie storage. I know how to check the cookies in request header in node js, but what I’m struggling with now is how frequently I have to send a request from react app to node js server. also, I’m not sure if I can just set interval in users because of memory leaking issues. then, should I just use useEffect hook to refresh access token?

please let me know the general mechanism of using refresh token and access token.

I tried to use setInterval in useEffect hook that depends on the state that contains interval id. I expected it automatically sends a request around 10 minutes before the access token that user has expires. but, it seemed like the app’s performance has significantly decreased.

2

Answers


    • Auth/Access token is something that is required for the user/request to be authorized to get the desired data from an API endpoint. This token will have a lifespan of 1hr-7days depending on the requirement.(The lifespan and validation can be implemented using JWT)
    • Refresh token is something that is required by the server/endpoint to create a new auth token before expiry.

    IMPLEMENTATION

    You can send a refresh token along with every API call to the server
    so that new auth token and a new refresh token is created after every request
    and is sent back to the Client. (In case of no api calls done for 7 days, you
    can run a script or an event which calls the API every 6 days which will keep
    the auth token valid infinitely)

    Login or Signup to reply.
  1. You don’t need to use your refresh token until your access token is expired.

    Access token is used in the request header (typically in the "Authorization") to tell the server that a perticuallar user is allowed to perform certain acitons. Refresh token is used to obtain a new access token when the old one expires. Namely, you should call your "/refresh-token" api whenever your previous api call returns 401 Unauthorized. And it could be done by interceptor.

    Here are some steps of how it works:

    1. Call api and returns 401 Unauthorized (that means access token expired)
    2. In your response interceptor, save the failed url, call "/refresh-token" api, and put the new access token in your storage.
    3. Use the new access token to make the original api call again.

    You should also consider whether to make your refresh token last forever, how to implement the interceptor if multiple requests return 401 at the same time (because you don’t want/need to call "/refresh-token" multiple times), etc.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search