Cookies and
Sessions in Web
Engineering
UNDERSTANDING THE FUNDAMENTALS, APPLICATIONS AND BEST
PRACTICES
What are Cookies?
Basic Definition:
• Web Cookies, also known simply as cookies, are small pieces of data
sent from a website and stored on a user's web browser while the user is
browsing that website.
• Each time the user loads the website, the browser sends the cookie back
to the server to notify the website of the user's previous activity.
Primary Function:
• Cookies are primarily used for session tracking, personalization, and
storing information about users' browsing activities.
Types of Cookies
Session Cookies:
• Definition: These are temporary cookies that are deleted once you close
your browser.
• Use Case: Commonly used to keep track of your actions during a
browsing session, like remembering items in a shopping cart.
Persistent Cookies:
• Definition: These cookies remain on your device for a set period specified
in the cookie even after the browser is closed.
• Use Case: Used for remembering login information, preferences, and
other customization functions for repeated visits.
Types of Cookies
Secure Cookies:
• Definition: These cookies can only be transmitted over secure, encrypted
connections (HTTPS).
• Use Case: Typically used for security purposes to authenticate users and
prevent fraudulent use of login credentials.
HttpOnly Cookies:
• Definition: These cookies cannot be accessed by client-side scripts and
are used mainly for protecting against cross-site scripting (XSS) attacks.
• Use Case: Often used in conjunction with secure cookies for security in
web applications.
How cookies work?
Cookie Creation and Transmission:
• Cookies are created when a server sends a ‘set-cookie’ header in response to
a browser request. The browser then stores this cookie and sends it back
to the server with subsequent requests to the same domain.
Role in HTTP:
• HTTP is stateless; cookies help maintain state across sessions by storing user
data like preferences and login status.
Lifecycle:
• Involves creation, storage, transmission with requests, and eventual expiration
or deletion.
Uses of Cookies
User Authentication:
• Cookies are crucial in managing login sessions. When a user logs in, the
server creates a session ID stored in a cookie, which is used for maintaining
the session across different pages.
Shopping Carts:
• E-commerce sites use cookies to keep track of items users have added to their
shopping carts as they navigate through the site, ensuring a seamless
shopping experience.
Tracking and Analytics:
• Cookies help in tracking user behavior on a website, providing valuable
insights for analytics. This data is used to understand user interactions,
improve website functionality, and measure the effectiveness of advertising
campaigns.
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function (req, res) {console.log('Cookies: ', req.cookies)
console.log('Signed Cookies: ', req.signedCookies)
})
app.listen(8080)
Limitations of Cookies
Size Restrictions:
• Cookies are limited in size, typically up to 4KB. This restricts the amount of
information that can be stored, making them unsuitable for large data storage.
Security Concerns:
• Cookies can be vulnerable to theft and manipulation. If not secured properly
(e.g., with Secure and HttpOnly flags), they can be exploited for cross-site
scripting (XSS) and cross-site request forgery (CSRF) attacks.
Dependency on Client-Side Storage:
• Cookies rely on the user's browser for storage. If a user switches devices or
browsers, the stored information is not transferred, leading to a lack of
continuity.
Performance Impact:
• Each HTTP request includes cookies, which can increase the load time,
especially if there are numerous or large cookies.
What are Sessions?
Basic Definition:
• A Session in web development refers to a period of interaction between a
user’s browser and a web server. It's used to store information about the
user across multiple HTTP requests.
Function and Purpose:
• Unlike cookies, which are stored on the user’s browser, session data is
typically stored on the server side.
• Sessions are used to maintain a consistent user experience, holding
information such as user preferences, login status, and shopping cart
contents over the course of a browser session.
Types of Sessions
User Sessions:
• Definition: Sessions that track individual user activities and preferences
throughout a website visit.
• Use Case: Common in e-commerce for tracking items in a shopping cart or
user login status.
Database-Backed Sessions:
• Definition: Sessions where session data is stored in a database, offering
better security and scalability.
• Use Case: Ideal for applications with a large number of users or when session
data needs to be preserved over a long period.
Types of Sessions
Cookie-Based Sessions:
• Definition: Sessions that store all session data within a cookie on the user’s
browser.
• Use Case: Suitable for smaller amounts of data and when ease of scalability is
a priority.
API Sessions:
• Definition: Sessions created for each API call, particularly in service-oriented
architectures.
• Use Case: Used in applications that interact with various APIs, where each call
needs to be authenticated and tracked.
How Sessions Work
Initiation of a Session:
• A session starts when a user first requests a page from a web application. The
server generates a unique session identifier (session ID) for this interaction.
Storing Session ID:
• The session ID is typically stored in a cookie on the user’s browser, although it can
also be passed via the URL or hidden form fields in situations where cookies are
disabled.
Session ID Transmission:
• With each subsequent HTTP request from the user’s browser, the session ID is
sent back to the server, either through a cookie, URL, or hidden form fields.
Retrieving Session Data:
• Upon receiving the session ID, the server retrieves the corresponding session data
from its store, allowing the application to maintain a continuous user experience
across multiple requests.
Session Expiration:
• Sessions are configured to expire after a certain period of inactivity or when the
browser is closed, ensuring that session data does not persist indefinitely for
security reasons.
Uses of Sessions
1. User Authentication:
• Sessions are crucial for maintaining user authentication status. After a user
logs in, the session stores the authentication status, allowing the user to
navigate through secured areas of a website without needing to log in
repeatedly.
2. Shopping Cart Functionality:
• E-commerce websites use sessions to track items a user has added to their
shopping cart. This allows the cart to persist as the user continues shopping,
even across different pages.
3. Access Control and Security:
• Sessions help in managing access to restricted resources on a website. They
ensure that only authenticated users can access certain pages or
functionalities.
4. Analytical Tracking:
• Sessions are used to track user behavior within a website for analytical
purposes, helping in understanding user navigation patterns and preferences
for website optimization.
Example
var express = require('express’);
var session = require('express-session');
var app = express();
app.get('/', function(req, res){
if(req.session.page_views){
req.session.page_views++;
res.send("You visited this page " + req.session.page_views + " times");
} else {
req.session.page_views = 1;
res.send("Welcome to this page for the first time!");
}
});
app.listen(3000);
Limitations of Sessions
Server Resource Consumption:
• Sessions typically store data on the server, which can consume significant server
memory, especially with a large number of concurrent users. This can impact server
performance and scalability.
Session Expiration Management:
• Managing session expiration can be challenging. If session duration is too short,
users may be inconvenienced. If too long, it poses a security risk, especially for
inactive sessions.
Dependency on Cookies:
• While not always, sessions often rely on cookies to store the session ID on the
client side. Users disabling cookies can disrupt the session mechanism, leading to
a degraded user experience.
Cross-Device Limitations:
• Sessions are typically bound to the user’s browser. If the user switches devices or
browsers, the session does not persist, leading to a discontinuous experience.
Cookies vs Sessions: