The Power and Pitfalls of Cookies in Web Development with Express.js

Rehmat Sayany
3 min readSep 23, 2023

--

Web developers have long utilized cookies as a tool to enhance user experience, track sessions, and manage small bits of data. But like all tools, there’s a correct way to wield cookies — especially in the context of Express.js.

What Are Cookies?

Cookies are tiny pieces of data stored on the user’s browser. When a user visits a website, the site can set a cookie on the user’s machine. On subsequent visits, the browser sends this cookie back to the server, allowing the server to “remember” certain details about the user.

The Benefits of Cookies in Express.js

  1. Session Management: Easily the most popular use case. Cookies can track user logins, shopping cart contents, or any other temporary data.
  2. Personalization: Cookies remember user preferences, ensuring a tailored browsing experience.
  3. Tracking and Analytics: Cookies can help monitor user behavior, providing valuable insights into user engagement.
  4. State Maintenance: The web is stateless. Cookies provide a way to retain stateful information between requests.

The Pitfalls of Using Cookies

Can Other Web Applications See My Cookies?

No, they can’t. Browsers implement a security measure called the Same-Origin Policy, ensuring that cookies set by one site can’t be read by another. However, this doesn’t mean cookies are completely private:

  1. Third-party Cookies: These are set by domains other than the one the user visits. They’re mostly used for online advertising and tracking users across different sites. Privacy concerns have led to increased restrictions on third-party cookies.

Express.js and Cookies

Express.js, a popular Node.js framework, doesn’t have built-in cookie handling in its core. However, integrating cookies is straightforward, thanks to middleware like cookie-parser.

Setting Up Cookies in Express:

  1. Install cookie-parser:
npm install cookie-parser

2. Use the middleware:

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

3. Setting a Cookie:

app.get('/setcookie', (req, res) => {
res.cookie('user', 'John Doe', { maxAge: 900000, httpOnly: true });
res.send('Cookie has been set');
});

4. Accessing Cookies:

app.get('/getcookie', (req, res) => {
const user = req.cookies['user'];
res.send(`Hello, ${user}`);
});

Why Not to Store Sensitive Information in Cookies?

  1. Eavesdropping Risks: Cookies can be intercepted, especially on unencrypted connections.
  2. XSS Attacks: Vulnerable sites can have their cookies stolen.
  3. CSRF Exploits: Cookies might be misused to perform unauthorized actions on a site.
  4. Unintentional Exposures: Developers might mistakenly expose cookies in logs or error messages.
  5. Regulatory Compliance: GDPR, CCPA, and other laws require proper handling of personal data. Misuse of cookies can lead to non-compliance.
  6. Limitations of Cookies: Size constraints and potential deletion by users make cookies an unreliable storage mechanism.
  7. Lack of Encryption: By default, cookies are in plaintext. They can be read by anyone with access.

What Not to Store in Cookies?

Given the potential risks:

  • Never store passwords, even if encrypted.
  • Avoid personal identification information (PII) like Social Security numbers, addresses, or phone numbers.
  • Refrain from storing confidential data or API keys.
  • Avoid full authentication tokens or session details.

Maximizing the Power of Cookies in Express.js:

  1. Use Secure and HttpOnly Flags: Secure ensures transmission only over HTTPS. HttpOnly prevents access via JavaScript, mitigating some XSS risks.
  2. Set Expiry: Short-lived cookies reduce the window of opportunity for potential misuse.
  3. Implement SameSite Attribute: This can help prevent CSRF attacks by ensuring the cookie is sent only when requests originate from the same site.
  4. Leverage JSON Web Tokens (JWT): Instead of storing data directly in cookies, use JWT to store session data on the server.

Conclusion

Cookies, when used judiciously, offer a robust method for improving user experience, especially in Express.js applications. By understanding their strengths and potential pitfalls, developers can strike a balance between functionality and security.

--

--

Rehmat Sayany
Rehmat Sayany

Written by Rehmat Sayany

Full Stack developer @westwing passionate about NodeJS, TypeScript, React JS and AWS.

Responses (1)