The core node:http module allows Node.js to transfer data over the HyperText Transfer Protocol without external framework abstractions (like Express or Fastify), handling HTTP requests, headers, status codes, and stream responses directly.
flowchart LR
A["HTTP Client (Browser/cURL)"] -->|"GET /api/status HTTP/1.1"| B["http.Server"]
B -->|"IncomingMessage (req)"| C["Route Handler Router"]
C -->|"ServerResponse (res)"| D["res.writeHead(200) + res.end()"]
D -->|"JSON Stream Payload"| A
import http from 'node:http';
import { URL } from 'node:url';
const PORT = 8080;
const server = http.createServer(async (req, res) => {
// Parse URL and Query parameters
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
const method = req.method;
// Set standard Security & JSON Headers
res.setHeader('Content-Type', 'application/json');
res.setHeader('X-Powered-By', 'Node.js Core HTTP Module');
if (method === 'GET' && pathname === '/api/users') {
const role = parsedUrl.searchParams.get('role') || 'all';
res.statusCode = 200;
return res.end(JSON.stringify({
status: 'success',
filter: role,
data: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
}));
}
if (method === 'POST' && pathname === '/api/users') {
let body = '';
for await (const chunk of req) {
body += chunk;
}
try {
const payload = JSON.parse(body);
res.statusCode = 201;
return res.end(JSON.stringify({ message: 'User Created', user: payload }));
} catch (err) {
res.statusCode = 400;
return res.end(JSON.stringify({ error: 'Invalid JSON Body Payload' }));
}
}
// Fallback 404 Route
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Route Not Found' }));
});
server.listen(PORT, () => {
console.log(`HTTP Server running at http://localhost:${PORT}`);
});
JSON.parse with try...catch blocks to protect server instances from crashing on malformed payloads.for await...of: Use asynchronous iterators to collect incoming request payload chunks easily and safely.server.keepAliveTimeout and server.headersTimeout to mitigate Slowloris Denial of Service (DoS) attacks.Add a GET /health route handler to the server above that returns { status: "UP", uptime: process.uptime() } with HTTP status 200 OK.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.