Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Managing HTTP Cookies in Node.js

Tech 1

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);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.