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

What are Deep Learning Frameworks?

March 28, 2024

How to Set Up Your First WordPress Website on Cloudways? (Step-by-Step for Beginners)

June 19, 2025

Image Enhancement: Top 10 Techniques in Deep Learning

May 16, 2024
X (Twitter) Instagram LinkedIn
Arunangshu Das Blog Wednesday, August 20
  • 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:July 11, 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

How AI is Transforming Software Development

September 25, 2024

Image Enhancement: Top 10 Techniques in Deep Learning

May 16, 2024

YOLO Algorithm: An Introduction to You Only Look Once

May 13, 2024

5 Common Mistakes in Backend Optimization

February 8, 2025
Don't Miss

The Role of Firewalls: 6 Proven Ways to Powerfully Safeguard Your Information

August 13, 20256 Mins Read

In the third quarter of 2022 alone, nearly 15 million data breaches were reported. With…

Padding in Image Processing: Why It Matters and How It Works

April 11, 2024

REST API Authentication Methods

July 10, 2025

Scaling Adaptive Software Development for Large Enterprises

January 21, 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

Streamlining Your Workflow: How Containerization in DevOps Boosts Efficiency

June 14, 2025

6 Types of Neural Networks You Should Know

February 8, 2025

Power of Deep Learning in Unsupervised Learning

February 28, 2024
Most Popular

7 Essential Tips for Fine-Tuning AI Models

February 9, 2025

Masterfully Scaling Your WooCommerce Store with Cloudways: A 2025 Growth Case Study

June 25, 2025

Top 8 Frontend Performance Optimization Strategies

February 17, 2025
Arunangshu Das Blog
  • About Me
  • Contact Us
  • Write for Us
  • Advertise With 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.