typescriptbeginner

Native HTTP Server

Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.

typescript
import http from 'http';
import { URL } from 'url';

type Handler = (req: http.IncomingMessage, res: http.ServerResponse) => void;

// Simple router
const routes = new Map<string, Handler>();

function registerRoute(method: string, path: string, handler: Handler) {
  routes.set(`${method} ${path}`, handler);
}

// JSON response helper
function json(res: http.ServerResponse, data: unknown, status = 200) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(data));
}

// Parse JSON body
async function parseBody<T>(req: http.IncomingMessage): Promise<T> {
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    req.on('data', (chunk: Buffer) => chunks.push(chunk));
    req.on('end', () => {
      try {
        resolve(JSON.parse(Buffer.concat(chunks).toString()));
      } catch (e) {
        reject(new Error('Invalid JSON body'));
      }
    });
    req.on('error', reject);
  });
}

// Register routes
registerRoute('GET', '/health', (_req, res) => {
  json(res, { status: 'ok', uptime: process.uptime() });
});

registerRoute('GET', '/api/users', (_req, res) => {
  json(res, [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ]);
});

registerRoute('POST', '/api/users', async (req, res) => {
  const body = await parseBody<{ name: string }>(req);
  json(res, { id: Date.now(), name: body.name }, 201);
});

// Server
const server = http.createServer((req, res) => {
  const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
  const key = `${req.method} ${url.pathname}`;
  const handler = routes.get(key);

  if (handler) {
    handler(req, res);
  } else {
    json(res, { error: 'Not Found' }, 404);
  }
});

const PORT = Number(process.env.PORT) || 3000;
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Sponsored

Deploy Node.js APIs on Railway

Use Cases

  • Lightweight API server without frameworks
  • Health check endpoints
  • Quick prototyping

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.