Difference between Access Token and Refresh Token

Access tokens are short-lived tokens that allow users to seamlessly interact with a system without requiring frequent authentication. However, since these tokens expire after a short duration, refresh tokens are issued alongside them. Refresh tokens have a longer lifespan and are used to generate new access tokens when the existing ones expire. This ensures continuous access without requiring the user to log in again.
In a Node.js application using Express.js and MongoDB, token-based authentication can be implemented with libraries like jsonwebtoken
(JWT). The access token is typically stored in memory or local storage, while the refresh token is securely stored in an HTTP-only cookie or database to prevent misuse. When an access token expires, the client sends a request with the refresh token to obtain a new access token, maintaining a smooth user experience while enhancing security.
To implement this in an Express.js application:
Generate Access and Refresh Tokens – When a user logs in, generate both tokens using
jsonwebtoken
and send the access token in the response while storing the refresh token securely.Store Tokens Securely – Access tokens can be stored in local storage or session storage, while refresh tokens should be stored in an HTTP-only cookie or database.
Handle Token Expiry – When an access token expires, the client sends a request to an endpoint (e.g.,
/refresh-token
) with the refresh token to obtain a new access token.Verify Tokens – Middleware can be used to validate access tokens for protected routes to ensure secure API access.
Logout Mechanism – When a user logs out, the refresh token should be invalidated by removing it from the database or marking it as expired.
This approach ensures a balance between security and usability, preventing unauthorized access while minimizing user interruptions.
Subscribe to my newsletter
Read articles from Rohit Lokhande directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by