How to create a simple HTTP server in Node.js

· Category: Node.js

Short answer

Use the built-in http module to create a server with http.createServer() and listen on a port using .listen().

Steps

  1. Import the http module with const http = require('http');.
  2. Create a server using http.createServer((req, res) => { ... }).
  3. Inside the callback, set response headers with res.writeHead(200, { 'Content-Type': 'text/plain' });.
  4. Send response data with res.end('Hello World\n');.
  5. Start listening on a port with server.listen(3000, () => console.log('Server running'));.

Tips

  • For production, consider using a framework like Express.js or Fastify to handle routing and middleware efficiently.
  • Always set appropriate Content-Type headers so browsers interpret responses correctly.

Common issues

  • EADDRINUSE means another process is already using the port. Change the port or kill the existing process.
  • Forgetting to call res.end() can cause the client to hang indefinitely waiting for the response to finish.