In this lesson, you will learn how to use the Expect: 100-continue handshake to save bandwidth by rejecting unauthorized large payloads before they are even transmitted.
The Problem: Wasted Bandwidth
When a client sends a very large file or data payload (like a 1GB video upload), the default HTTP behavior is to send the entire body immediately. If your server determines after receiving that data that the user isn't authenticated, all that network traffic was wasted.
The Solution: The Handshake
The Expect: 100-continue header allows the client to ask the server for permission before sending the body.
- The client sends the headers only, including
Expect: 100-continue. - The server inspects these headers (e.g., checking an
Authorizationtoken). - If the server is happy, it sends a
100 Continuestatus code. - The client then proceeds to send the request body.
- If the server is unhappy, it sends a
401 Unauthorizedor403 Forbiddenimmediately, and the client stops, saving the user's data usage.
Implementing in Node.js
In Node.js, the http server module exposes the checkContinue event to handle this specifically. Instead of letting the body stream in, you intercept the request:
const http = require('http');
const server = http.createServer((req, res) => {
// This runs only if we gave the "Continue" signal
req.on('data', (chunk) => console.log(`Received ${chunk.length} bytes`));
});
server.on('checkContinue', (req, res) => {
const auth = req.headers['authorization'];
if (auth === 'secret-token') {
// Permission granted: send the 100 Continue signal
res.writeContinue();
// Now trigger the request handler logic
server.emit('request', req, res);
} else {
// Permission denied: reject immediately
res.statusCode = 401;
res.end('Unauthorized');
}
});
By listening for checkContinue, you gain control over the request lifecycle, ensuring your server isn't forced to process large streams from unauthorized clients. This protects your memory and network resources from being overwhelmed by rejected traffic.
Key Takeaway: The Expect: 100-continue handshake lets you validate headers before accepting a large request body, allowing you to reject unauthorized uploads without wasting bandwidth.