Skip to content

Repository files navigation

🧠 Custom HTTP Server in TypeScript

This is a custom-built HTTP server built using Node.js and TypeScript to understand how HTTP works under the hood — without using any external libraries like Express.js.

🚀 Features

  • ✅ Manually parses HTTP requests using Node's net module
  • 🔁 Handles persistent and non-persistent connections (Connection: keep-alive/close)
  • 🌍 Supports basic routing:
    • / → Returns Hello World!
    • /echo/:text → Echoes text back
    • /user-agent → Returns User-Agent header
    • /files/:filename (GET) → Serves files from a directory
    • /files/:filename (POST) → Saves uploaded file
  • 📦 Supports gzip compression if Accept-Encoding: gzip is provided
  • 🧠 Manually handles headers, request body, and byte streams

🛠️ How It Works

1. Create TCP Server

Using net.createServer(), a TCP server is started on localhost:4221. All data is received as raw byte streams.

2. Parse HTTP Request

The server splits requests on \r\n\r\n, separates the request line and headers, and stores them in a JS object.

3. Handle Routes

  • / – Returns "Hello World!"
  • /echo/:message – Echoes back the message; gzips it if Accept-Encoding: gzip is sent.
  • /user-agent – Returns the value of the User-Agent header.
  • /files/:filename:
    • GET – Reads the file from the directory passed with --directory flag.
    • POST – Writes the incoming body to that file path.

4. Handle Headers

  • Content-Length is calculated manually.
  • Content-Encoding is set when gzipping.
  • Connection is honored to keep-alive or close the socket.

🧪 Example Usage

Start the server:

ts-node index.ts --directory ./data

About

I have build my own http server to learn more about request and response and how this work under the hood and also learn new things.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages