Close Menu
Arunangshu Das Blog
  • SaaS Tools
    • Business Operations SaaS
    • Marketing & Sales SaaS
    • Collaboration & Productivity SaaS
    • Financial & Accounting SaaS
  • Web Hosting
    • Types of Hosting
    • Domain & DNS Management
    • Server Management Tools
    • Website Security & Backup Services
  • Cybersecurity
    • Network Security
    • Endpoint Security
    • Application Security
    • Cloud Security
  • IoT
    • Smart Home & Consumer IoT
    • Industrial IoT
    • Healthcare IoT
    • Agricultural IoT
  • Software Development
    • Frontend Development
    • Backend Development
    • DevOps
    • Adaptive Software Development
    • Expert Interviews
      • Software Developer Interview Questions
      • Devops Interview Questions
    • Industry Insights
      • Case Studies
      • Trends and News
      • Future Technology
  • AI
    • Machine Learning
    • Deep Learning
    • NLP
    • LLM
    • AI Interview Questions
  • Startup

Subscribe to Updates

Subscribe to our newsletter for updates, insights, tips, and exclusive content!

What's Hot

Exploring the Latest Features in React

July 23, 2024

What is Cybersecurity? An Amazing Beginner’s Introduction

May 28, 2025

Choosing the Right Frontend Development Frameworks for Your Web Project

May 25, 2025
X (Twitter) Instagram LinkedIn
Arunangshu Das Blog Thursday, June 26
  • Write For Us
  • Blog
  • Gallery
  • Contact Me
  • Newsletter
Facebook X (Twitter) Instagram LinkedIn RSS
Subscribe
  • SaaS Tools
    • Business Operations SaaS
    • Marketing & Sales SaaS
    • Collaboration & Productivity SaaS
    • Financial & Accounting SaaS
  • Web Hosting
    • Types of Hosting
    • Domain & DNS Management
    • Server Management Tools
    • Website Security & Backup Services
  • Cybersecurity
    • Network Security
    • Endpoint Security
    • Application Security
    • Cloud Security
  • IoT
    • Smart Home & Consumer IoT
    • Industrial IoT
    • Healthcare IoT
    • Agricultural IoT
  • Software Development
    • Frontend Development
    • Backend Development
    • DevOps
    • Adaptive Software Development
    • Expert Interviews
      • Software Developer Interview Questions
      • Devops Interview Questions
    • Industry Insights
      • Case Studies
      • Trends and News
      • Future Technology
  • AI
    • Machine Learning
    • Deep Learning
    • NLP
    • LLM
    • AI Interview Questions
  • Startup
Arunangshu Das Blog
  • Write For Us
  • Blog
  • Gallery
  • Contact Me
  • Newsletter
Home»Software Development»Frontend Development»All about storing cookies in frontend
Frontend Development

All about storing cookies in frontend

Arunangshu DasBy Arunangshu DasJuly 17, 2024Updated:February 26, 2025No Comments5 Mins Read
Facebook Twitter Pinterest Telegram LinkedIn Tumblr Copy Link Email Reddit Threads WhatsApp
Follow Us
Facebook X (Twitter) LinkedIn Instagram
Share
Facebook Twitter LinkedIn Pinterest Email Copy Link Reddit WhatsApp Threads

Managing cookies and tokens is a critical aspect of web development, playing a crucial role in securing user data and maintaining session integrity. Whether you’re dealing with short-term access tokens, long-term refresh tokens, or user preferences, knowing where and how to store these pieces of information can make a significant difference in the security and performance of your application.

Understanding Cookies

Cookies are small pieces of data stored on the client side. They have several key attributes:

  • Name: The cookie’s identifier.
  • Value: The data associated with the cookie.
  • Domain: The domain that the cookie belongs to.
  • Path: The URL path that must exist in the requested URL for the browser to send the Cookie header.
  • Expires/Max-Age: The expiration date or maximum age of the cookie.
  • Secure: A flag that indicates if the cookie should only be transmitted over secure protocols like HTTPS.
  • HttpOnly: A flag that makes the cookie inaccessible to JavaScript’s Document.cookie API, reducing the risk of cross-site scripting (XSS) attacks.
  • SameSite: A flag that controls whether the cookie is sent with cross-site requests, providing some protection against cross-site request forgery (CSRF) attacks.

Types of Cookies

  1. Session Cookies: These cookies are temporary and are deleted once the user closes the browser. They are ideal for storing information that should only persist during a single browsing session.
  2. Persistent Cookies: These cookies remain on the user’s device for a specified period, even after the browser is closed. They are used for long-term storage, such as remembering user preferences or login states.

Access Tokens and Refresh Tokens

Access Tokens: These tokens are used to authenticate API requests. They typically have a short lifespan to minimize security risks in case they are compromised.

Refresh Tokens: These tokens are used to obtain new access tokens without requiring the user to log in again. They have a longer lifespan than access tokens and are generally stored more securely.

Best Practices for Storing Cookies and Tokens

1. Storing Tokens in Cookies

  • HttpOnly and Secure Flags: Always set the HttpOnly and Secure flags on cookies to protect against XSS and ensure that they are only transmitted over HTTPS.
  • SameSite Attribute: Use the SameSite attribute to mitigate CSRF attacks. Set it to Strict or Lax depending on your application’s needs.

2. Storing Tokens in Local Storage

  • Not Recommended for Sensitive Data: Avoid storing sensitive information like access and refresh tokens in local storage as it is accessible via JavaScript and vulnerable to XSS attacks.
  • Use for Non-Sensitive Data: Local storage can be used for non-sensitive data that needs to persist between sessions.

3. Storing Tokens in Session Storage

  • Session Lifespan: Session storage is cleared when the page session ends. It is safer than local storage but still vulnerable to XSS.
  • Use for Short-Term Data: Suitable for storing data that should only persist during a single session.

4. Storing Tokens in Memory

  • In-Memory Storage: Storing tokens in memory (e.g., within JavaScript variables) can be an effective way to manage tokens during a session.
  • Vulnerability: Tokens stored in memory are lost when the page is refreshed or closed, making it a secure yet temporary solution.

Implementing Secure Storage Practices

Using HttpOnly Cookies for Access Tokens

// Example of setting a HttpOnly, Secure, and SameSite cookie
res.cookie('accessToken', accessToken, {
  httpOnly: true,
  secure: true,
  sameSite: 'Strict', // or 'Lax'
  maxAge: 3600000 // 1 hour
});

Using Secure Storage for Refresh Tokens

// Example of setting a HttpOnly, Secure, and SameSite cookie for refresh token
res.cookie('refreshToken', refreshToken, {
  httpOnly: true,
  secure: true,
  sameSite: 'Strict',
  maxAge: 604800000 // 7 days
});

Handling Token Expiration and Refreshing Tokens

  1. Access Token Expiration: Ensure your access tokens have a short expiration time, typically 15 minutes to 1 hour.
  2. Refresh Token Flow: Implement a refresh token flow to obtain new access tokens without requiring the user to log in again. Storing Cookies.

Refresh Token Endpoint Example

app.post('/refresh-token', async (req, res) => {
  const { refreshToken } = req.cookies;
  if (!refreshToken) {
    return res.status(401).send('Unauthorized');
  }

  // Verify refresh token
  jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
    if (err) {
      return res.status(403).send('Forbidden');
    }

    // Generate new access token
    const accessToken = jwt.sign({ username: user.username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '15m' });
    res.cookie('accessToken', accessToken, {
      httpOnly: true,
      secure: true,
      sameSite: 'Strict',
      maxAge: 900000 // 15 minutes
    });
    res.status(200).send({ accessToken });
  });
});

Ensuring Secure Token Transmission

  • HTTPS Only: Ensure your application uses HTTPS to encrypt data in transit.
  • Secure Cookie Flag: Set the Secure flag on cookies to ensure they are only sent over HTTPS.

Conclusion

Storing cookies and tokens securely is a critical aspect of web development. By understanding the various storage options and implementing best practices, we can enhance the security and performance of your applications. Use Http Only and Secure cookies for sensitive data like access and refresh tokens, leverage session storage for short-term needs, and always prioritize secure transmission methods like HTTPS.

access token Access Tokens and Refresh Tokens All About Storing Cookies in Frontend Best Practices for Tokens cookies Frontend Frontend Development Handling Token Expiration refresh token Storing Cookies in Front
Follow on Facebook Follow on X (Twitter) Follow on LinkedIn Follow on Instagram
Share. Facebook Twitter Pinterest LinkedIn Telegram Email Copy Link Reddit WhatsApp Threads
Previous ArticleDevelopment and Deployment Lifecycle of Software
Next Article The Necessity of Scaling Systems Despite Advanced Traffic-Handling Frameworks

Related Posts

Speed Up Your Site: A Practical Guide to Frontend Performance Optimization Tool

June 16, 2025

The Next Frontier: Exploring the Future of Frontend Development

June 13, 2025

Choosing the Right Frontend Development Frameworks for Your Web Project

May 25, 2025
Add A Comment
Leave A Reply Cancel Reply

Top Posts

10 Applications of Code Generators You Should Know

February 17, 2025

The Role of Big Data in Business Decision-Making: Transforming Enterprise Strategy

February 26, 2025

Why a Good Backend Developer is the Industry’s Key Decision-Maker

July 14, 2024

5 Ways AI is Transforming Stock Market Analysis

February 18, 2025
Don't Miss

VGG Architecture Explained: How It Revolutionized Deep Neural Networks

December 18, 20245 Mins Read

Introduction to VGG Architecture In the ever-evolving field of deep learning, convolutional neural networks (CNNs)…

Lasso Regression

March 31, 2024

What is caching, and how does it improve application performance?

November 4, 2024

6 Key Strategies for Backend Security Enhancement

February 14, 2025
Stay In Touch
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • LinkedIn

Subscribe to Updates

Subscribe to our newsletter for updates, insights, and exclusive content every week!

About Us

I am Arunangshu Das, a Software Developer passionate about creating efficient, scalable applications. With expertise in various programming languages and frameworks, I enjoy solving complex problems, optimizing performance, and contributing to innovative projects that drive technological advancement.

Facebook X (Twitter) Instagram LinkedIn RSS
Don't Miss

The Science Behind Fine-Tuning AI Models: How Machines Learn to Adapt

February 9, 2025

Is a Machine Learning Model a Statistical Model?

March 28, 2024

SaaS and Traditional Software Business Models: 7 key differences to know

June 13, 2025
Most Popular

Comparing VGG and LeNet-5 Architectures: Key Differences and Use Cases in Deep Learnings

December 9, 2024

Database Design Principles for Scalable Applications

July 23, 2024

Caching Strategies for High-Performance Backends

July 23, 2024
Arunangshu Das Blog
  • About Me
  • Contact Me
  • Write for Us
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
  • Article
  • Blog
  • Newsletter
  • Media House
© 2025 Arunangshu Das. Designed by Arunangshu Das.

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.