Node.js HTTP & HTTPS Core Modules - Building Fast Web Servers From Scratch

Before web frameworks like Express or Fastify existed, developers built web servers using Node.js's built-in http and https modules. Understanding how pure HTTP servers handle routing, HTTP headers, status codes, and request streams will make you a much stronger backend engineer.

Building a Complete HTTP Router with Pure Node.js

The following example demonstrates routing, query parameter parsing, and POST payload handling without any external third-party NPM packages:

// pure-http-server.js
const http = require('http');
const { URL } = require('url');

const PORT = 3000;

const server = http.createServer((req, res) => {
  // Parse full URL and search parameters
  const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
  const path = parsedUrl.pathname;
  const method = req.method;

  // Helper to send JSON responses
  const sendJson = (statusCode, data) => {
    res.writeHead(statusCode, {
      'Content-Type': 'application/json',
      'X-Powered-By': 'Veewom Pure Node.js Engine'
    });
    res.end(JSON.stringify(data, null, 2));
  };

  // Route 1: GET /
  if (method === 'GET' && path === '/') {
    return sendJson(200, {
      message: 'Welcome to Veewom Pure HTTP Server API',
      status: 'active'
    });
  }

  // Route 2: GET /api/greet?name=Rahul
  if (method === 'GET' && path === '/api/greet') {
    const name = parsedUrl.searchParams.get('name') || 'Guest';
    return sendJson(200, { greeting: `Hello, ${name}!` });
  }

  // Route 3: POST /api/feedback (Handling Incoming Stream Body)
  if (method === 'POST' && path === '/api/feedback') {
    let bodyChunks = [];

    // Collect streaming data chunks
    req.on('data', (chunk) => {
      bodyChunks.push(chunk);
    });

    // Entire stream received
    req.on('end', () => {
      try {
        const bodyBuffer = Buffer.concat(bodyChunks);
        const parsedBody = JSON.parse(bodyBuffer.toString('utf8'));

        console.log('Received feedback:', parsedBody);

        return sendJson(201, {
          success: true,
          message: 'Feedback received successfully!',
          dataReceived: parsedBody
        });
      } catch (err) {
        return sendJson(400, { error: 'Invalid JSON payload received' });
      }
    });

    return; // Don't end response prematurely!
  }

  // Fallback 404 Not Found
  return sendJson(404, { error: 'Route not found' });
});

server.listen(PORT, () => {
  console.log(`Pure HTTP server running at http://localhost:${PORT}/`);
});

Enabling HTTPS with SSL/TLS Certificates

In production, all traffic must be encrypted over HTTPS. The https module accepts your SSL certificates generated by Let's Encrypt or OpenSSL:

const https = require('https');
const fs = require('fs');

const sslOptions = {
  key: fs.readFileSync('certs/privkey.pem'),
  cert: fs.readFileSync('certs/fullchain.pem')
};

https.createServer(sslOptions, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Secure HTTPS connection established with Veewom server!
');
}).listen(8443, () => {
  console.log('Secure HTTPS server live on port 8443');
});

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between req.url and the full request URL?

In the built-in HTTP module, 'req.url' only contains the path and query string (e.g. '/api/users?page=2'), omitting the protocol and host. To parse it completely with modern WHATWG URL API, pass: 'new URL(req.url, `http://${req.headers.host}`)';.

Q2. How do you parse an incoming POST request JSON body with pure Node.js?

Because 'req' is a Readable Stream, you collect data chunks by listening to the 'data' event, concatenate them into a Buffer, and on the 'end' event, convert the buffer to a string and call 'JSON.parse()'.

Q3. How do you enable HTTPS in Node.js?

Use the 'https' module and pass an SSL options object containing your private key and certificate: 'https.createServer({ key: fs.readFileSync("server.key"), cert: fs.readFileSync("server.crt") }, handler).listen(443)'.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

URL & QueryString Handling

Parse URLs and query parameters cleanly with WHATWG API.

Express.js Overview

Transition from pure HTTP to modern Express frameworks.

First Node Application

Basic HTTP server setup walkthrough.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!