Managing HTTP Cookies in Node.js
Cookies remain a relevant mechanism for storing small amounts of string data in web applications, despite the prevalence of LocalStorage and SessionStorage. In HTTP communication, cookies are automatically included in requests sent from the client to the server, and servers can set cookies with broader control than clients.
Setting Cookies in Node.js
Using the built-in http module, you can create a server with createServer(), which accepts a callback function with request and response parameters. To set cookies, utilize the response.setHeader() method.
Basic Cookie Setup
const http = require('http');
const app = http.createServer((request, response) => {
response.setHeader('Set-Cookie', 'session=active;');
response.end('Response sent');
});
app.listen(3000);
Configuring Path Scope
For authentication cookies, set the path to / to ensure they are included in all requests.
response.setHeader('Set-Cookie', 'session=active; path=/;');
Enforcing Server-Side Access with httpOnly
To prevent client-side JavaScript from accessing or modifying a cookie, add the httpOnly flag.
response.setHeader('Set-Cookie', 'session=active; httpOnly;');
Defining Expiration with expires
Set an expiration date for cookies using the expires attribute. For example, to expire after one day:
function getExpirationDate() {
const current = new Date();
current.setTime(current.getTime() + 86400000); // 24 hours in milliseconds
return current.toUTCString();
}
response.setHeader('Set-Cookie', `session=active; expires=${getExpirationDate()};`);
Comprehensive Authentication Example
const http = require('http');
function generateExpiry() {
const date = new Date();
date.setTime(date.getTime() + 86400000);
return date.toUTCString();
}
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', `authToken=abc123; path=/; httpOnly; expires=${generateExpiry()}`);
res.end('Authenticated');
});
server.listen(3000);
Retrieving Cookies
Cookies sent by the client are accesisble in the request.headers.cookie property.
const http = require('http');
const server = http.createServer((req, res) => {
const rawCookies = req.headers.cookie;
console.log('Received cookies:', rawCookies);
res.end('Processed');
});
server.listen(3000);
Parsing Cookies into an Object
The cookie string follows a key=value; format. Convert it to a JavaScript object for easier manipulation.
const http = require('http');
const server = http.createServer((req, res) => {
const cookieString = req.headers.cookie || '';
const parsedCookies = {};
cookieString.split(';').forEach(pair => {
if (!pair.trim()) return;
const [key, value] = pair.split('=');
parsedCookies[key.trim()] = value ? value.trim() : '';
});
console.log('Parsed cookies:', parsedCookies);
res.end('Parsing complete');
});
server.listen(3000);