Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
JWT Authentication With Refresh Tokens
Next article icon

JWT Authentication With Refresh Tokens

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Authentication is a critical part of web applications. Using JWT (JSON Web Tokens) for authentication is common, but adding refresh tokens provides an added layer of security and convenience. In this article, we’ll discuss how to implement JWT authentication with refresh tokens.

JWT (JSON Web Token)

JWT is a compact and URL-safe way to represent claims between two parties, typically for authentication. It’s widely used in modern web applications for securely transmitting information, such as user details.

Refresh Tokens

A refresh token is a special kind of token used to obtain a new access token after the old one expires. Refresh tokens allow you to maintain a user session without re-authenticating every time the access token expires.

Auth Persistence:

We can easily persist users between refreshes and login without any credentials. We can create a new route called refresh, whenever a token expires or a user refreshes we can get a new access token by sending a request to this route

Steps to Installation the express module:

Step 1: Run the following commands to initialize the project and create an index file & env file. (Make sure you have node and npm installed)

npm init -y

Step 2: Installing required packages

npm install express cookie-parser dotenv jsonwebtoken 

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {     "cookie-parser": "^1.4.6",     "dotenv": "^16.3.1",     "express": "^4.18.2",     "jsonwebtoken": "^9.0.2", }

Explanation: In `index.js`, authentication logic involves creating an Express app with login and refresh routes. The login route validates credentials, responding with a refresh token and access token on a successful match, while the refresh route verifies the token for a new access token or raises an authorization error.

Example: We will now implement two routes login & refresh. The below code is for index.js:

javascript
const dotenv = require('dotenv'); const express = require('express'); const cookieparser = require('cookie-parser'); const jwt = require('jsonwebtoken') const bodyParser = require('body-parser');  // Configuring dotenv dotenv.config(); const app = express();  // Setting up middlewares to parse request body and cookies app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieparser());  const userCredentials = {     username: 'admin',     password: 'admin123',     email: '[email protected]' }  app.post('/login', (req, res) => {     // Destructuring username & password from body     const { username, password } = req.body;      // Checking if credentials match     if (username === userCredentials.username &&         password === userCredentials.password) {          //creating a access token         const accessToken = jwt.sign({             username: userCredentials.username,             email: userCredentials.email         }, process.env.ACCESS_TOKEN_SECRET, {             expiresIn: '10m'         });         // Creating refresh token not that expiry of refresh          //token is greater than the access token          const refreshToken = jwt.sign({             username: userCredentials.username,         }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '1d' });          // Assigning refresh token in http-only cookie          res.cookie('jwt', refreshToken, {             httpOnly: true,             sameSite: 'None', secure: true,             maxAge: 24 * 60 * 60 * 1000         });         return res.json({ accessToken });     }     else {         // Return unauthorized error if credentials don't match         return res.status(406).json({             message: 'Invalid credentials'         });     } })  app.post('/refresh', (req, res) => {     if (req.cookies?.jwt) {          // Destructuring refreshToken from cookie         const refreshToken = req.cookies.jwt;          // Verifying refresh token         jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET,             (err, decoded) => {                 if (err) {                      // Wrong Refesh Token                     return res.status(406).json({ message: 'Unauthorized' });                 }                 else {                     // Correct token we send a new access token                     const accessToken = jwt.sign({                         username: userCredentials.username,                         email: userCredentials.email                     }, process.env.ACCESS_TOKEN_SECRET, {                         expiresIn: '10m'                     });                     return res.json({ accessToken });                 }             })     } else {         return res.status(406).json({ message: 'Unauthorized' });     } })  app.get('/', ((req, res) => {     res.send("Server");     console.log("server running"); }))  app.listen(8000, () => {     console.log(`Server active on http://localhost:${8000}!`); }) 

.env: The below code is for .env which is used to store your sensitive credentials like API keys:

PORT = 8000 ACCESS_TOKEN_SECRET=MYSECRETACCESS REFRESH_TOKEN_SECRET=MYREFRESHTOKENSECRET

Output:

Why Use Refresh Tokens with JWT?

  1. Security: Access tokens are short-lived, reducing the risk of long-term exposure if compromised.
  2. Convenience: Refresh tokens allow for automatic re-authentication without requiring the user to log in again.
  3. Persistent Sessions: Refresh tokens enable long-term user sessions by renewing the access token when it expires.

Conclusion

Implementing JWT authentication with refresh tokens is a secure and efficient way to handle user sessions in web applications. By storing refresh tokens in HttpOnly cookies, you can prevent access token theft while maintaining seamless user experience. This approach ensures that your app can handle both short-lived access tokens and secure, prolonged user sessions.


Next Article
JWT Authentication With Refresh Tokens

K

ksangtiani13
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • NodeJS-Questions

Similar Reads

    JWT Authentication In Node.js
    In modern web development, ensuring secure and efficient user authentication is paramount. JSON Web Tokens (JWT) offer a robust solution for token-based authentication, enabling secure transmission of user information between parties. This article provides a step-by-step approach to implementing JWT
    3 min read
    Mastering JWT authentication in Express
    While creating any application it is very important to add authentication to ensure that only authorized users can access the protected resources. A JSON Web Token (JWT) is a JSON object utilized to securely transmit information between two parties over the web. Primarily employed in authentication
    4 min read
    Authentication and Authorization with OAuth
    OAuth (Open Authorization) is the open standard for token-based authentication and authorization on the Internet. It can allow third-party services to exchange information without exposing the user credentials. In this article, we will guide you on how to implement the OAuth in the MERN stack applic
    6 min read
    How to Handle Authentication with Postman API Testing?
    Authentication is very important for securing access to resources and data. When testing APIs, handling authentication correctly is important to ensure that your tests can interact with secured endpoints effectively. Postman, a popular API testing tool, provides robust features for handling various
    4 min read
    Multi Factor authentication using MERN
    This article will guide you through creating a Multi-Factor Authentication (MFA) project using the MERN. This project aims to enhance security by implementing a multi-step authentication process. Users will be required to provide multiple forms of identification for access, adding an extra layer of
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences