Mastering Requests and Responses

8 min read

Imagine you are running a busy pizza shop (the server). You have hungry customers (clients) walking in constantly. If you, the chef, cannot understand what the customer ordered, or if you forget to actually hand them the pizza after baking it, you are going to have a terrible time. You need a way to reliably receive their orders, dietary restrictions, and payment details, and then hand back the correct pizza with a clear receipt.

In Express.js, this communication happens entirely through Requests and Responses. By the end of this guide, you will know exactly how to handle incoming data and craft the perfect outgoing reply, just like industry professionals do.

Before we dive into the concepts, let's set up the modern, standard Express boilerplate so you can test these concepts on your own machine.

The Standard Boilerplate Setup

According to the official Express documentation, here is the absolute latest standard for getting an Express server running. We will also include two built-in/standard middlewares necessary for our topics.

javascript
// 1. Import Express and necessary parsers
const express = require('express');
const cookieParser = require('cookie-parser'); // npm install cookie-parser

// 2. Initialize the application
const app = express();
const port = 3000;

// 3. Middlewares (We will explain why these are needed later!)
app.use(express.json()); 
app.use(cookieParser());

// 4. Your routes will go here
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 5. Start listening for customers
app.listen(port, () => {
  console.log(`Server listening on port ${port} 🍕`);
});

1. Deep Dive into the Request Object (Headers, Body, Cookies)

Definition

The request object (usually shortened to req) represents the incoming HTTP request. It contains exact properties for the request query string, parameters, body, HTTP headers, cookies, and network data.

The Problem

When a client hits your server endpoint (e.g., POST /order), how do you know what they ordered? How do you know if they are logged in? How do you know if they are using a mobile app or a web browser? The URL alone is not enough to carry all this heavy information.

The Concept

The req object solves this by acting as a massive, organized filing cabinet of information provided by the client. Under the hood, Express builds this on top of Node.js's native http.IncomingMessage object, but Express makes it much friendlier to use.

Let's look at the three most frequently used compartments in this filing cabinet: Headers, Body, and Cookies.

🕵️ Headers (req.headers)

Headers are metadata sent by the client. They contain context about the request, such as the type of device making the request, the type of content being sent, and authorization tokens.

In our pizza shop simulation, headers are like the customer showing you their VIP membership card before placing an order.

Industry Practice: The most common use of headers is checking the Authorization header to verify if a user is logged in.

javascript
app.get('/secret-pizza', (req, res) => {
  // Reading headers is as simple as accessing the object properties
  const authHeader = req.headers['authorization'];
  const userAgent = req.headers['user-agent'];

  if (!authHeader) {
    return res.status(401).send('No VIP card shown!');
  }
  
  res.send(`Welcome, VIP using ${userAgent}!`);
});

📦 Body (req.body)

The body is the actual payload of data the client is sending to the server. If a user fills out a form or sends JSON data to create a new user, that data lives in the body.

The Catch: By default, Express is incredibly unopinionated. It does not know if the incoming body is JSON, a file upload, or plain text. If you try to read req.body without telling Express how to parse it, Express will just look at you with the blank, empty stare of undefined, making you question your sanity for exactly 45 minutes.

To fix this, we use a middleware: app.use(express.json()). This tells Express: "Hey, if a request comes in with JSON, parse it into a neat JavaScript object for me."

javascript
app.post('/order', (req, res) => {
  // Because we used express.json(), req.body is now a readable object!
  const pizzaType = req.body.type;
  const quantity = req.body.quantity;

  console.log(`Cooking ${quantity} ${pizzaType} pizzas...`);
  res.send('Order received!');
});

🍪 Cookies (req.cookies)

Cookies are small pieces of data stored on the client's browser that are automatically sent with every request to your server.

Like the body, Express does not parse cookies by default. You must install and use the cookie-parser middleware. Once applied, you can read cookies effortlessly.

Industry Practice: Cookies are frequently used to store session IDs or user preferences (like dark mode vs. light mode).

javascript
app.get('/profile', (req, res) => {
  // Reading a specific cookie named "sessionId"
  const session = req.cookies.sessionId;

  if (session) {
    res.send('Loading your saved preferences...');
  } else {
    res.send('Welcome, new customer!');
  }
});

2. Crafting Responses (Send, JSON, and Redirects)

Definition

The response object (usually shortened to res) represents the HTTP response that an Express app sends back to the client when it receives an HTTP request.

The Problem

Once your server has processed the request (baked the pizza), the client is left hanging, staring at a loading spinner. If you don't explicitly send something back, the client will eventually time out and throw an error. You need a way to deliver data, HTML, or instructions back to the client efficiently.

The Concept

The res object handles this outbox. It is built on top of Node's http.ServerResponse object. Let's look at the most heavily utilized methods in the industry.

📨 res.send()

This is the versatile, all-purpose response method. When you pass data into res.send(), Express automatically detects what kind of data it is and sets the appropriate Content-Type header for the client.

  • Pass a string? Express sends plain text (or HTML if it looks like HTML).
  • Pass an array or object? Express formats it as JSON.
javascript
app.get('/greeting', (req, res) => {
  res.send('<h1>Hello, World!</h1>'); // Sends HTML
});

🗄️ res.json()

While res.send() can send JSON, res.json() is the industry standard for APIs. It explicitly formats the response as JSON and ensures the headers are strictly set to application/json. It is marginally safer and more explicit when building modern web services.

javascript
app.get('/api/menu', (req, res) => {
  const menu = [
    { id: 1, name: 'Margherita', price: 10 },
    { id: 2, name: 'Pepperoni', price: 12 }
  ];
  
  // Explicitly sends JSON. The standard for modern APIs.
  res.json(menu); 
});

🔀 res.redirect()

Sometimes, the response isn't data; it's a set of directions. If a user tries to access a page they shouldn't, or if they successfully log in, you want to bounce them to a different URL.

javascript
app.get('/old-menu', (req, res) => {
  // The client will automatically be redirected to the new URL
  res.redirect('/api/menu'); 
});

3. Setting HTTP Status Codes Semantically

Definition

HTTP status codes are standardized three-digit numbers sent by the server to indicate the outcome of the request.

The Problem

Imagine a client requests user data, but the database is down. You could send back a JSON response saying {"error": "Database is down"}. However, the client's browser/app has to parse that whole string to figure out something went wrong. This is inefficient.

The Concept

Status codes solve this by giving the client a standardized, immediate summary of what happened. Express allows you to set this using res.status().

In our pizza shop, a status code is the color of the receipt. Green means everything is great. Yellow means you did something wrong. Red means the kitchen just caught on fire.

Industry Standard Codes You Will Actually Use:

  • 200 (OK): The default. Everything went perfectly.
  • 201 (Created): Success, and a new resource (like a new user or a new order) was officially created in the database.
  • 400 (Bad Request): The client messed up. They sent missing or invalid data.
  • 401 (Unauthorized): The client is not authenticated (Not logged in).
  • 403 (Forbidden): The client is logged in, but not allowed to be here (E.g., a regular user trying to access the admin dashboard).
  • 404 (Not Found): The requested resource does not exist.
  • 500 (Internal Server Error): The server's code broke, or the database crashed. Not the client's fault.
javascript
app.post('/login', (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    // 400 Bad Request: Client forgot to send password!
    res.status(400);
    res.send('Username and password are required.');
    return;
  }

  // 200 OK: Everything is fine.
  res.status(200);
  res.send('Login successful!');
});

4. Chaining Response Methods for Cleaner Code

Definition

Method chaining is the practice of calling multiple methods on the same object consecutively in a single line of code.

The Problem

In the status code example above, we wrote:

javascript
res.status(400);
res.send('Username and password are required.');

Writing this across multiple lines every time you respond to a request makes your route handlers unnecessarily long, clunky, and harder to read.

The Concept

Because res.status() returns the response object itself after setting the status code, you can immediately chain your sending method (send, json, or redirect) right onto it. This is the defacto standard for writing clean Express code.

javascript
app.post('/register', (req, res) => {
  const { email } = req.body;

  if (!email) {
    // Clean, one-line chained response
    return res.status(400).json({ error: 'Email is required' });
  }

  // Save user to database...
  
  // Clean, one-line chained response for success
  res.status(201).json({ message: 'User successfully created!' });
});

Note: Always remember to use return when sending an error response early. Otherwise, Express will keep reading the code below it, try to send a second response, and crash with a "Cannot set headers after they are sent to the client" error!


References & Further Reading

Challenge

You are building a secure API endpoint to create user profiles. Your task is to implement the logic for a POST route at /api/profile that validates incoming requests based on headers, cookies, and the request body before creating a profile.

Requirements:

  1. Authentication: The endpoint must first check for an Authorization header. The request is only valid if this header has the exact value of 'Bearer valid-token'. If it's missing or incorrect, the server should respond immediately.
  2. Session Validation: After passing authentication, the endpoint must check for a cookie named sessionId. If the cookie does not exist, the request is considered forbidden.
  3. Body Validation: If both authentication and session checks pass, the endpoint must validate the request body. The body must be a JSON object containing both a username and an email property. If either is missing, the request is invalid.
  4. Success Response: If all validations are successful, the server should indicate that the resource was created.

Response Specifications:

  • For an authentication failure, respond with a status code of 401 and the JSON body { "error": "Unauthorized" }.
  • For a session validation failure, respond with a 403 status and the JSON body { "error": "Forbidden: No active session" }.
  • For a body validation failure, respond with a 400 status and the JSON body { "error": "Bad Request: Missing username or email" }.
  • For a successful request, respond with a 201 status and a JSON body { "message": "Profile created successfully", "user": { "username": "...", "email": "..." } }, where the user object contains the data from the request body.

Note: Use method chaining for all responses (e.g., res.status(code).json(...)) and ensure you use return to halt execution after sending an error response.

Expected result

Your code should correctly implement the POST /api/profile endpoint such that:

  • A request with an incorrect or missing Authorization header receives a 401 status and the appropriate JSON error.
  • A request with a valid header but no sessionId cookie receives a 403 status and its corresponding JSON error.
  • A request with a valid header and cookie but a missing username or email in the body receives a 400 status and the relevant JSON error.
  • A valid request containing the correct header, cookie, and body format receives a 201 status and a success message including the user data sent in the request body.
  • All responses should be sent using chained methods like res.status().json().
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.