What are the best practices for storing and sending JWT tokens in the browser? (2024)

Last updated on Jan 26, 2024

  1. All
  2. Front-End Development

Powered by AI and the LinkedIn community

1

Use HTTPS

2

Choose the right storage option

3

Use the HttpOnly and Secure flags

4

Use short-lived tokens

5

Validate and decode your tokens

6

Here’s what else to consider

JWT tokens are a popular way to authenticate users and authorize access to web applications. They are compact, self-contained, and cryptographically signed pieces of data that can be exchanged between the browser and the server. But how do you store and send them securely and efficiently? Here are some best practices to follow.

Top experts in this article

Selected by the community from 24 contributions. Learn more

What are the best practices for storing and sending JWT tokens in the browser? (1)

Earn a Community Top Voice badge

Add to collaborative articles to get recognized for your expertise on your profile. Learn more

  • Mohammed Mortada Senior Full-Stack Software Engineer (Extensive Experience in The MERN Stack)

    What are the best practices for storing and sending JWT tokens in the browser? (3) What are the best practices for storing and sending JWT tokens in the browser? (4) What are the best practices for storing and sending JWT tokens in the browser? (5) 6

  • Syed Moazam Ali MERN Stack Developer 👨💻 |Beta MLSA 🔆| Web Dev Head @GDSC UETT | React Js | React Native | Next Js Developer |…

    What are the best practices for storing and sending JWT tokens in the browser? (7) 2

  • Heri Hehe Setiawan Team Lead - Front End at FinanSys | Finance Automation

    What are the best practices for storing and sending JWT tokens in the browser? (9) 2

What are the best practices for storing and sending JWT tokens in the browser? (10) What are the best practices for storing and sending JWT tokens in the browser? (11) What are the best practices for storing and sending JWT tokens in the browser? (12)

1 Use HTTPS

The first and most important rule is to always use HTTPS for your web application. HTTPS encrypts the communication between the browser and the server, preventing anyone from intercepting or tampering with your JWT tokens. Without HTTPS, your tokens are vulnerable to man-in-the-middle attacks, replay attacks, or eavesdropping.

Add your perspective

Help others by sharing more (125 characters min.)

  • Syed Moazam Ali MERN Stack Developer 👨💻 |Beta MLSA 🔆| Web Dev Head @GDSC UETT | React Js | React Native | Next Js Developer | JavaScript |Typescript | Software Engineering Student
    • Report contribution

    Based on my experience, it's crucial to fortify JWT token security in the browser by employing HttpOnly and Secure flags, limiting access to HTTPS. Opting for secure, HttpOnly cookies enhances protection against CSRF threats. Implementing thoughtful strategies like token expiration, refresh mechanisms, and SameSite attributes is paramount for a robust security framework. Additionally, considering encryption for sensitive data and incorporating revocation mechanisms adds an extra layer of control over access privilege.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (21) 2

    Unhelpful
  • Heri Hehe Setiawan Team Lead - Front End at FinanSys | Finance Automation
    • Report contribution

    Implementing HTTPS in your web application involves obtaining an SSL/TLS certificate, configuring your server to use it, and updating your application to use "https://" URLs. Enable automatic HTTP to HTTPS redirection, employ Content Security Policy (CSP), and address any mixed content issues. Regularly test and monitor your application for security vulnerabilities. This not only secures JWT tokens but also enhances user trust and potentially improves SEO rankings, making it a critical practice for web development.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (30) 2

    Unhelpful
    • Report contribution

    Storing and transmitting JWT tokens in the browser via HTTPS is essential for ensuring the security of authentication and authorization processes in web development. HTTPS encrypts the data exchanged between the client and server, preventing eavesdropping and man-in-the-middle attacks. This encryption safeguards the confidentiality and integrity of sensitive information, such as JWT tokens, during transmission. In addition to enhancing security, using HTTPS aligns with browser security policies, builds user trust, and ensures compliance with regulatory standards. It provides a foundational layer of protection against various network-based threats, making it a fundamental practice in securing web applications.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (39) 1

    Unhelpful
  • Asif Ali Senior Frontend Engineer @ 31 Green | Web Development | Scalability | Architect | Javascript | Typescript | MaterialUI | ReactJs | NextJS | RTK Query | Jest | NodeJs | Next14
    • Report contribution

    Always transmit JWT tokens over HTTPS to encrypt data in transit. This prevents attackers from intercepting and manipulating the tokens, ensuring a secure communication channel between the browser and the server.

    Like
    Unhelpful

Load more contributions

2 Choose the right storage option

The next question is where to store your JWT tokens in the browser. There are three common choices, each with their own advantages and drawbacks depending on the security and usability requirements. Local storage is the most straightforward option, as it allows you to store your tokens in the browser's memory and access them from any script. However, this is also the least secure option, as it leaves your tokens vulnerable to cross-site scripting (XSS) attacks. Session storage is similar to local storage, but it limits the scope of your tokens to the current browser tab or window, reducing the risk of XSS attacks, though also meaning that your tokens will be lost if the user closes or refreshes the tab or window. Finally, cookies are a more traditional option, as they allow you to store your tokens in the browser's headers and send them automatically with every request to the server. This protects your tokens from XSS attacks, but exposes them to cross-site request forgery (CSRF) attacks.

Add your perspective

Help others by sharing more (125 characters min.)

  • Heri Hehe Setiawan Team Lead - Front End at FinanSys | Finance Automation
    • Report contribution

    The choice of where to store your JWT tokens in the browser is a critical consideration in your authentication strategy. Each option—local storage, session storage, and cookies—comes with its own set of trade-offs. Local storage provides simplicity and accessibility across scripts but is vulnerable to XSS attacks. Session storage limits token scope to the current browser tab, reducing XSS risk but potentially causing token loss upon tab closure. On the other hand, using cookies offers a traditional approach, protecting tokens from XSS but making them susceptible to CSRF attacks.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (56) 2

    Unhelpful
    • Report contribution

    When deciding on a storage option for JWT tokens in the browser, consider using HTTP-only cookies for enhanced security. HTTP-only cookies prevent client-side JavaScript access, mitigating the risk of XSS attacks. Ensure proper configuration, including the Secure attribute for HTTPS-only transmission and attention to the SameSite attribute to control cross-site requests. In summary, prioritize HTTP-only cookies for their security features, unless specific use cases necessitate Web Storage, in which case, implement measures to mitigate associated risks. Regularly reassess security practices to align with evolving best practices and emerging threats.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (65) 2

    Unhelpful

Load more contributions

3 Use the HttpOnly and Secure flags

If you choose to store your JWT tokens in cookies, you should use the HttpOnly and Secure flags to enhance their security. The HttpOnly flag prevents scripts from accessing your cookies, making them immune to XSS attacks. The Secure flag ensures that your cookies are only sent over HTTPS, making them immune to network attacks.

Add your perspective

Help others by sharing more (125 characters min.)

  • Mohammed Mortada Senior Full-Stack Software Engineer (Extensive Experience in The MERN Stack)
    • Report contribution

    After setting the `Secure` flag in the `Set-Cookie` header, it's crucial to understand that if your website is not served over HTTPS, the browser will not send the cookie with the `Secure` flag. This means that the cookie will not be sent at all, and the user's session may be disrupted.In other words, if your website is not using HTTPS, setting the `Secure` flag will have no effect, and the cookie will not be sent. This can lead to unexpected behavior and potential security vulnerabilities.To ensure that the `Secure` flag works as intended, you need to make sure that your website is properly configured to use HTTPS. This involves obtaining an SSL/TLS certificate and configuring your web server to serve your website over HTTPS.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (74) What are the best practices for storing and sending JWT tokens in the browser? (75) What are the best practices for storing and sending JWT tokens in the browser? (76) 6

    Unhelpful
  • Heri Hehe Setiawan Team Lead - Front End at FinanSys | Finance Automation

    When opting to store JWT tokens in cookies, it's imperative to implement additional security measures for robust protection. Utilize the HttpOnly flag to restrict script access to cookies, rendering them impervious to XSS attacks. This precautionary step prevents malicious scripts from tampering with or exfiltrating sensitive token data.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (85) 1

    Unhelpful
    • Report contribution

    When storing and transmitting JWT tokens in the browser, it's crucial to enhance security by utilizing the HttpOnly and Secure flags when setting cookies. The HttpOnly flag ensures that the cookie is inaccessible to JavaScript, thwarting potential cross-site scripting (XSS) attacks. Meanwhile, the Secure flag mandates that the cookie is transmitted solely over secure (HTTPS) connections, bolstering protection against network-based threats. By incorporating these flags along with appropriate expiration settings, developers can fortify the integrity of JWT token storage, minimizing the risk of unauthorized access and ensuring a more resilient authentication mechanism.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (94) 1

    Unhelpful

Load more contributions

4 Use short-lived tokens

Another best practice is to use short-lived tokens for your web application. Short-lived tokens reduce the window of opportunity for attackers to steal or reuse your tokens. They also make it easier to revoke access or refresh tokens when needed. You can use the exp (expiration) claim in your JWT tokens to specify their validity period, and use a separate refresh token to obtain new access tokens when they expire.

Add your perspective

Help others by sharing more (125 characters min.)

  • Ikrom Aulia Fahdi Chief Technology Officer at Level Up
    • Report contribution

    You can use short-lived JWT token (access token) for access the API. When the access token is expired, you can request new access token by generating from refresh token + old access token. The request token has longer exp (expiration) then access token, so when access token is expired, user doesn't need to login again.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (103) 1

    Unhelpful
  • Asif Ali Senior Frontend Engineer @ 31 Green | Web Development | Scalability | Architect | Javascript | Typescript | MaterialUI | ReactJs | NextJS | RTK Query | Jest | NodeJs | Next14
    • Report contribution

    Employ short expiration times for JWT tokens to minimize the window of opportunity for attackers. This practice limits the potential damage caused by a compromised token and promotes better security hygiene by regularly refreshing tokens.

    Like
    Unhelpful

Load more contributions

5 Validate and decode your tokens

The last best practice is to validate and decode your tokens properly on both the browser and the server side. Validation ensures that your tokens are authentic, unexpired, and issued by a trusted source. Decoding allows you to extract the payload data from your tokens, such as the user's identity and permissions. You can use libraries or frameworks that support JWT standards to handle these tasks for you, or implement your own logic using the signature and header of your tokens.

Add your perspective

Help others by sharing more (125 characters min.)

  • Ikrom Aulia Fahdi Chief Technology Officer at Level Up
    • Report contribution

    Use the asymmetric JWT for the better security because it use 2 keys, public dan private key. The server encode JWT token using private key, and client decode JWT token using public key. Don't forget to use strong secret too.

    Like
    Unhelpful
  • Asif Ali Senior Frontend Engineer @ 31 Green | Web Development | Scalability | Architect | Javascript | Typescript | MaterialUI | ReactJs | NextJS | RTK Query | Jest | NodeJs | Next14
    • Report contribution

    Before trusting the information in a JWT token, validate its signature to ensure its integrity and decode it securely. Validating the token's claims, such as expiration time and issuer, helps prevent accepting tampered or expired tokens.

    Like
    Unhelpful

Load more contributions

6 Here’s what else to consider

This is a space to share examples, stories, or insights that don’t fit into any of the previous sections. What else would you like to add?

Add your perspective

Help others by sharing more (125 characters min.)

  • Asif Ali Senior Frontend Engineer @ 31 Green | Web Development | Scalability | Architect | Javascript | Typescript | MaterialUI | ReactJs | NextJS | RTK Query | Jest | NodeJs | Next14
    • Report contribution

    Implement token refreshing mechanisms to maintain user sessions without requiring frequent reauthentication. Additionally, consider using token revocation mechanisms in case a token needs to be invalidated before its natural expiration. Regularly review and update security practices to stay resilient against evolving threats.

    Like

    What are the best practices for storing and sending JWT tokens in the browser? (136) What are the best practices for storing and sending JWT tokens in the browser? (137) 2

    Unhelpful

Front-end Development What are the best practices for storing and sending JWT tokens in the browser? (138)

Front-end Development

+ Follow

Rate this article

We created this article with the help of AI. What do you think of it?

It’s great It’s not so great

Thanks for your feedback

Your feedback is private. Like or react to bring the conversation to your network.

Tell us more

Report this article

More articles on Front-end Development

No more previous content

  • How can CSS-in-JS improve your front-end development workflow? 359 contributions
  • How can CSS preprocessors and frameworks help you create unique styles? 251 contributions
  • How can you improve your code quality and standards with linters and formatters? 252 contributions
  • How do you keep your service workers scripts up to date? 82 contributions
  • How do you use a CSS preprocessor? 147 contributions
  • How do you design a front-end mockup? 127 contributions
  • What's the best front-end framework for your project? 131 contributions
  • How do you balance reliability and compatibility with innovation in front-end development? 126 contributions
  • How do you balance simplicity and flexibility with CSS frameworks? 44 contributions
  • How do you use hooks with React? 98 contributions
  • How can you get certified in front-end development? 103 contributions
  • How do you create a front-end security audit checklist? 67 contributions
  • How do you learn about Progressive Web Apps and Service Workers? 34 contributions
  • How can you overcome front-end development challenges in the current market? 99 contributions
  • How can you improve your front-end projects with design principles and user research? 66 contributions

No more next content

See all

More relevant reading

  • Front-end Development How do you secure JWT tokens in your front-end applications?
  • Web Development How can SameSite cookies prevent Cross-Site Request Forgery attacks?
  • Security Awareness How can browser extensions improve your web security?
  • Computer Repair How can you troubleshoot web browser issues like slow loading, pop-ups, and security warnings?

Help improve contributions

Mark contributions as unhelpful if you find them irrelevant or not valuable to the article. This feedback is private to you and won’t be shared publicly.

Contribution hidden for you

This feedback is never shared publicly, we’ll use it to show better contributions to everyone.

Are you sure you want to delete your contribution?

Are you sure you want to delete your reply?

What are the best practices for storing and sending JWT tokens in the browser? (2024)

FAQs

What are the best practices for storing and sending JWT tokens in the browser? ›

To keep them secure, you should always store JWTs inside an HttpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading and writing) from JavaScript running in the browser.

What are the best practices to store JWT? ›

To keep them secure, you should always store JWTs inside an HttpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading and writing) from JavaScript running in the browser.

How do I securely store JWT tokens in my browser? ›

Optimal Secure Solution: Save JWT Tokens in the browser's memory and store the refresh token in a cookie
  1. Step 1: Generate and issue tokens. ...
  2. Step 2: Save the JSON web token in the browser session. ...
  3. Step 3: Save the refresh token in a secure HttpOnly Cookie. ...
  4. Step 4: How to refresh the JSON web tokens.
May 9, 2023

Is it good practice to store JWT token in database? ›

To reiterate, whatever you do, don't store a JWT in local storage (or session storage). If any of the third-party scripts you include in your page is compromised, it can access all your users' tokens. To keep them secure, you should always store JWTs inside an httpOnly cookie.

Which of the following is the correct way to save a JWT in a user's browser? ›

JWT should be stored in cookies. You can use httponly and secure flags depending on your requirements. To protect from CSRF samesite cookie attribute can be set to strict if it generally fits your application - it will prevent logged-in users of your site to follow any link to your site from any other site.

How do I store a token in my browser? ›

Applications can use dedicated APIs, such as the Web Storage API or IndexedDB, to store tokens. Applications can also simply keep the token in memory or put them in cookies. Some storage mechanisms are persistent, and others are wiped after some period of time or when the page is closed or refreshed.

What is the best way to store JWT tokens in React? ›

JWT tokens are a popular form of token-based authentication because they are self-contained and can contain user information. We can use the js-cookie library to store JWT tokens in cookies in React. You should start by installing the library using npm install js-cookie or yarn add js-cookie .

Should JWT be stored in cookies or local storage? ›

Storing Your JWT/Auth Token

The attacker could then make false requests, modify your user's data in the database, and do a lot of damage for your application as well as users. Hence, it's always best to store JWTs in http only cookies.

What is the safest way to store auth tokens? ›

Auth0 recommends storing tokens in browser memory as the most secure option. Using Web Workers to handle the transmission and storage of tokens is the best way to protect the tokens, as Web Workers run in a separate global scope than the rest of the application.

What is the safest way to store access tokens? ›

We recommend storing tokens on the server, as this offers traditional web apps the maximum level of security. If this cannot be done, you should use encrypted session cookies so the client cannot read token values.

Is storing JWT in local storage safe? ›

Vulnerability to XSS Attacks: The primary security concern with Local Storage is its susceptibility to Cross-Site Scripting (XSS) attacks. If an attacker can inject malicious scripts into your web application, they can access Local Storage and retrieve the stored JWTs, leading to potential security breaches.

What is the best practice for JWT token expiration time? ›

Best Practices for JWT Expiration Timelines
  • Duration: Typically, 5 to 30 minutes.
  • Rationale: Minimizes the risk if a token is compromised.
  • Refresh Tokens: Use longer-lived refresh tokens to renew access tokens without user intervention.

What is the best way to store API tokens? ›

4 Use OAuth and JWT

JWT is a standard format that encodes your identity and claims in a signed and optionally encrypted token. By using OAuth and JWT, you can avoid storing and transmitting your keys and tokens directly, and instead rely on trusted providers and intermediaries to issue and verify them.

Should JWT be sent with every request? ›

Send the JWT to the client: The server will send the JWT to the client, which will store it for future use. Send the JWT with every request: When the client wants to access a protected resource on the server, it will send the JWT in the Authorization header of the HTTP request.

What is the difference between session storage and local storage? ›

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends. Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab.

What is more secure than JWT? ›

Secure: Opaque tokens do not contain any user information, making them more secure than JWT tokens. Flexible: Opaque tokens can be customized to store additional user information in the authorization server, which can be retrieved by the resource server when needed.

Should JWT be stored in cookie or session storage? ›

Storing JWT (JSON Web Token) in a cookie is considered safer than storing it in session storage or local storage for several reasons: Cookies are less vulnerable to Cross-Site Scripting (XSS) attacks than session storage or local storage.

Where should JWT be generated? ›

JWT must be created on client side for each call, which might consume some processing power and adds overhead to the implementation. The server must acquire user information from the database (or some kind of cache) for each call. The pre shared secret must be kept secret on client and server side.

What is the best practice for access token lifetime? ›

Access token lifetime

We recommend that you set the validity period of your token based on the security requirements of your API. For example, an access token that accesses a banking API should expire more quickly than one that accesses a to-do API. To learn more, see Update Access Token Lifetime.

Top Articles
Latest Posts
Article information

Author: Velia Krajcik

Last Updated:

Views: 6682

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.