KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
🟢

Node.js

Topic Hub & Articles

Node.js Intro

10 min

Node.js Get Started

10 min

Node.js Modules

10 min

Node.js HTTP Module

10 min

Node.js File System

10 min

Node.js URL Module

10 min

Node.js NPM

10 min

Node.js Events

10 min

Node.js Upload Files

10 min

Node.js Email

10 min

Node.js Buffer

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Streams

10 min

Node.js Crypto

10 min

Node.js OS Module

10 min

Node.js Path Module

10 min

Node.js Global Objects

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Process

10 min

Node.js Child Processes

10 min

Node.js Worker Threads

10 min

Node.js DNS Module

10 min

Node.js Query String

10 min

Recap Quiz

Gated

Milestone Assessment

MySQL Connect

10 min

MySQL Create Database

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js MySQL ORDER BY Clause

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Intro

10 min

MongoDB Create Database

10 min

MongoDB Create Collection

10 min

MongoDB Insert

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Find

10 min

MongoDB Query

10 min

MongoDB Sort

10 min

MongoDB Delete

10 min

MongoDB Update

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Limit

10 min

MongoDB Join

10 min

Progress
0%

0 / 35 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
Node.jsNode.js Tutorial
Lesson

Node.js HTTP Module

10 min reading
Free Course

Node.js HTTP Module: Building Web Servers and Routing Requests

The built-in node:http module lets Node.js listen on a TCP port, receive HTTP requests, and send HTML or JSON responses without external frameworks. Learning http.createServer() clarifies how Express, Fastify, and Next.js handle headers, status codes, and request streams under the hood.

Creating a Simple Multi-Route HTTP Server

Every incoming request invokes your (req, res) listener with an IncomingMessage stream (req) and a writable ServerResponse (res). Always set Content-Type headers explicitly and finish every branch with res.end().

import http from 'node:http';

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);

  if (req.method === 'GET' && url.pathname === '/health') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'healthy', uptime: process.uptime() }));
    return;
  }

  if (req.method === 'GET' && url.pathname === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('Welcome to the Node.js HTTP server.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ error: 'Route not found' }));
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000');
});

Reading POST Request Bodies Safely

Because req is a readable stream, POST JSON payloads arrive in chunks rather than all at once. Collect chunks inside an async loop (for await (const chunk of req)), enforce a maximum byte limit so huge payloads cannot exhaust RAM, and parse the combined string inside try / catch.

Common Mistakes to Avoid

  • Forgetting return after res.end(): Continuing into a fallback 404 branch after sending 200 throws ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent.
  • Reading req.url without parsing: Raw req.url includes query parameters (/users?page=2). Parse it with new URL(req.url, 'http://localhost') to separate pathname from searchParams.
  • Leaving no request timeout or body limit: Production HTTP servers should configure server.requestTimeout and reject oversized request bodies with HTTP 413.

Frequently Asked Questions

Why does http.createServer() receive two requests for / in a browser?

Browsers automatically request /favicon.ico alongside /. Return 204 No Content for /favicon.ico if you want clean request logs.

Can I use http directly for HTTPS in production?

Use node:https with TLS certificates for direct TLS termination, or run plain node:http behind a reverse proxy like Nginx or Cloudflare.

How do I read HTTP request headers in node:http?

Node.js automatically lowercases all incoming header names on req.headers, such as req.headers['authorization'] or req.headers['content-type'].

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground

Related Developer Tools & Topic Hub

Node.js Topic Hub
JSON Formatter
Validate, format, and minify JSON
Regex Tester
Test regular expression patterns
JWT Decoder
Inspect JSON Web Token payloads
All Node.js Articles
Deep-dive guides, tips & discussions
PreviousNode.js Modules
Continue JourneyNext: Node.js File System

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum