Demystifying HTTP: Request, Response, Headers, Params, Cookies, Query, and Authentication

Demystifying HTTP: Request, Response, Headers, Params, Cookies, Query, and Authentication

Understanding how web communication works is crucial for every web developer. Whether you're building frontend or backend applications, mastering the basics of HTTP will make you a better developer.

In this article, I’ll break down key HTTP concepts with practical examples in JavaScript using Node.js (Express) and the Fetch API to help you understand what really happens when a browser talks to a server.


HTTP Request and Response – The Foundation

When a user visits a website or submits a form, the browser (client) sends an HTTP request to the server, which replies with an HTTP response.

Request Contains:

  • Method (GET, POST, etc.)
  • URL
  • Headers
  • Parameters
  • Query strings
  • Cookies
  • Body (for POST/PUT)


Response Returns

  • Status code
  • Headers
  • Cookies
  • Response body (JSON, HTML, etc.)


Request Body

Used to send data in POST/PUT requests — like form inputs or JSON.

// Backend (Express)
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  res.json({ message: 'Data received', user: username });
});        
// Frontend (Fetch)
fetch('http://localhost:3000/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'john', password: '123456' })
});        



Headers

Metadata about the request or response. Sent as key-value pairs.

// Custom header for authentication
fetch('http://localhost:3000/data', {
  headers: {
    'Authorization': 'Bearer mysecrettoken'
  }
});        
// Backend reads header
const token = req.headers['authorization'];        

Cookies

Cookies store small pieces of data in the browser and are sent automatically with every request.

Set a cookie:

res.cookie('sessionId', 'abc123').json({ message: 'Cookie set' });        

Read a cookie:

const cookies = req.cookies;        

Special Note: -

In Express.js, to read cookies sent by the client, you need a special middleware called cookie-parser.

By default, Express does not automatically parse cookies from incoming requests. Cookies come as a raw string in the headers. To easily access them as an object (like req.cookies), you use the cookie-parser middleware.

Step-by-Step Explanation

01. Install the middleware

npm install cookie-parser        

02. Use it in your Express app

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

const app = express();

// Use middleware here 👇
app.use(cookieParser());        

03. Now you can access cookies like this

app.get('/read-cookies', (req, res) => {
  console.log(req.cookies); // 👉 Outputs all cookies as a JS object
  res.send('Cookies received');
});        

Example with Setting and Reading Cookies

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

app.use(cookieParser());

// Set a cookie
app.get('/set-cookie', (req, res) => {
  res.cookie('username', 'john');
  res.send('Cookie has been set');
});

// Read cookie
app.get('/read-cookie', (req, res) => {
  const cookies = req.cookies;
  res.json({ cookies });
});

app.listen(3000, () => console.log('Server running on port 3000'));        

Output (when you visit /read-cookie after /set-cookie)

{
  "username": "john"
}        


Article content

You can use cookies in Express without cookie-parser, but it’s more manual and complex. Here's a clear explanation with example code:

Example: Handling Cookies without cookie-parser


Set a Cookie Manually

const express = require('express');
const app = express();

// Set cookie
app.get('/set-cookie', (req, res) => {
  res.setHeader('Set-Cookie', 'username=john; HttpOnly');
  res.send('Cookie set manually');
});        


Read Cookie Manually

app.get('/read-cookie', (req, res) => {
  const rawCookie = req.headers.cookie; // e.g., "username=john; session=abc123"
  
  const parsedCookies = {};
  if (rawCookie) {
    rawCookie.split(';').forEach(cookie => {
      const [key, value] = cookie.trim().split('=');
      parsedCookies[key] = value;
    });
  }

  res.json({ cookies: parsedCookies });
});        


Article content

Recommendation

Use cookie-parser for simplicity and readability, especially in production apps. But understanding how to do it manually helps deepen your understanding of HTTP.


Path Parameters

Used in the URL path to identify a resource.

// URL: /user/123
app.get('/user/:id', (req, res) => {
  const id = req.params.id; // "123"
});        

Query Parameters

Used to filter or sort results. Sent after ? in the URL.

// URL: /products?category=books&sort=price
app.get('/products', (req, res) => {
  const query = req.query; // { category: 'books', sort: 'price' }
});        

Authentication

Used to verify identity and protect routes.

Bearer Token Example

Backend

app.get('/protected', (req, res) => {
  const token = req.headers['authorization'];

  if (token === 'Bearer mysecrettoken') {
    res.json({ message: 'Access granted' });
  } else {
    res.status(401).json({ message: 'Unauthorized' });
  }
});        

Frontend

fetch('http://localhost:3000/protected', {
  headers: {
    'Authorization': 'Bearer mysecrettoken'
  }
});        



Final Thoughts

Understanding how requests and responses work — including headers, cookies, parameters, queries, and authentication — is foundational to web development. This knowledge helps you:

  • Secure your APIs
  • Build reliable user authentication
  • Handle data properly between client and server

If you're a beginner, start experimenting with simple servers like the examples above. You'll get hands-on practice with concepts that power the entire web.


To view or add a comment, sign in

More articles by Uditha Vithanage

Others also viewed

Explore content categories