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
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)
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:
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.