← Back to TypeScript Course | Chapter 13: TypeScript with Node.js | Lesson 4 of 6

HTTP Module with Types

Node.js includes the http module for creating web servers without an external framework. TypeScript can type incoming requests, outgoing responses, and server configuration.

Creating an HTTP Server

Creating an HTTP server with Node's built-in http module and @types/node gives the createServer callback correctly typed IncomingMessage and ServerResponse parameters instead of untyped raw objects.

Example: Creating an HTTP Server

typescript
// import * as http from "http";
// const server = http.createServer((req, res) => { res.end("ok"); });
console.log("createServer's callback receives typed IncomingMessage/ServerResponse");

Typing Incoming Requests

Typing incoming requests means using IncomingMessage's properties like .url and .method, both of which are typed as possibly undefined, correctly reflecting that a malformed raw HTTP request can omit them.

Example: Typing Incoming Requests

typescript
// (req: http.IncomingMessage) => {
//   const url: string | undefined = req.url;
//   const method: string | undefined = req.method;
// }
console.log("req.url and req.method are typed as possibly undefined");

Routing with Types

Routing with types typically means switching on req.method and req.url with narrowed string comparisons, since the built-in http module has no router of its own — any routing structure is something you type yourself.

Example: Routing with Types

typescript
function route(method: string, url: string): string {
  if (method === "GET" && url === "/") return "home";
  return "not found";
}
console.log(route("GET", "/"));

Typed JSON Responses

Sending a typed JSON response means calling res.end(JSON.stringify(data)) where data's shape is defined by an interface, so a typo in a response field name gets caught before it ever reaches a client.

Example: Typed JSON Responses

typescript
interface ApiResponse { status: string }
const data: ApiResponse = { status: "ok" };
// res.end(JSON.stringify(data));
console.log(JSON.stringify(data));

Typed Server Configuration

Typed server configuration — like the port number or TLS options passed to createServer/listen — catches basic mistakes like passing a string where a ListenOptions object or number is actually expected.

Example: Typed Server Configuration

typescript
interface ListenOptions { port: number; host?: string }
const options: ListenOptions = { port: 8080 };
// server.listen(options.port);
console.log("Listening on port", options.port);
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.