TIL: Creating an HTTP Server With the Node.js http Module
Express is great but sometimes you need a server in five lines, not fifty. Node’s built-in http module handles it.
const http = require('http')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'ok' }))
})
server.listen(3000)
No package.json. No node_modules. Just run it with node server.js and curl localhost:3000.
I used this pattern constantly for quick webhook test servers, mock API endpoints, and debugging tools. When the whole thing fits in one file there is nothing to break.
How do I handle different routes?
Parse req.url and branch with if statements or a switch block. Add routing as the file grows.
Does this support HTTPS?
Use the https module with a certificate and key. Same API as http.