0
0
ExpressComparisonBeginner · 4 min read

Session vs Cookie in Express: Key Differences and Usage

In Express, a cookie is a small piece of data stored on the user's browser, while a session stores data on the server linked to a unique session ID saved in a cookie. Sessions are more secure and can hold sensitive data, whereas cookies are simpler but visible and modifiable by the user.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of sessions and cookies in Express.

FactorSessionCookie
Storage LocationServerUser's browser
Data Size LimitLarge (depends on server)Small (~4KB)
SecurityMore secure (data not exposed to client)Less secure (data visible and modifiable)
PersistenceExpires on logout or timeoutCan be persistent or session-based
UsageStore sensitive user dataStore simple data like preferences
RequiresSession middleware and cookie to store session IDJust cookie middleware
⚖️

Key Differences

Cookies are small text files saved directly on the user's browser. They can store simple data like user preferences or tokens but are limited in size and can be read or changed by the user, so they are not safe for sensitive information.

Sessions store data on the server side and only keep a unique session ID in a cookie on the client. This means the actual data is hidden from the user, making sessions more secure and suitable for storing sensitive data like login status or user roles.

Sessions require server memory or storage to keep data, while cookies rely on the browser. Sessions also need middleware like express-session to manage the session lifecycle, whereas cookies can be handled with cookie-parser or native methods.

⚖️

Code Comparison

This example shows how to set and read a cookie in Express.

javascript
import express from 'express';
import cookieParser from 'cookie-parser';

const app = express();
app.use(cookieParser());

app.get('/set-cookie', (req, res) => {
  res.cookie('username', 'alice', { maxAge: 900000, httpOnly: true });
  res.send('Cookie set');
});

app.get('/get-cookie', (req, res) => {
  const username = req.cookies.username || 'Guest';
  res.send(`Hello, ${username}`);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Visiting /set-cookie sets a cookie named 'username'. Visiting /get-cookie shows 'Hello, alice'.
↔️

Session Equivalent

This example shows how to use sessions in Express to store and read user data securely.

javascript
import express from 'express';
import session from 'express-session';

const app = express();

app.use(session({
  secret: 'mySecretKey',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 }
}));

app.get('/set-session', (req, res) => {
  req.session.username = 'alice';
  res.send('Session set');
});

app.get('/get-session', (req, res) => {
  const username = req.session.username || 'Guest';
  res.send(`Hello, ${username}`);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Visiting /set-session stores 'alice' in session. Visiting /get-session shows 'Hello, alice'.
🎯

When to Use Which

Choose cookies when you need to store small, non-sensitive data on the client side, like user preferences or theme settings, especially if you want the data to persist without server storage.

Choose sessions when you need to store sensitive or larger data securely on the server, such as login status, user roles, or shopping cart contents, because sessions keep data hidden from the user and are more secure.

Key Takeaways

Sessions store data securely on the server, while cookies store data on the user's browser.
Use cookies for small, non-sensitive data and sessions for sensitive or larger data.
Sessions require middleware like express-session; cookies can be handled with cookie-parser.
Cookies are limited in size and visible to users; sessions keep data hidden and safer.
Choose based on security needs and data size when managing user state in Express.