How to create a simple HTTP server in Node.js
Creating HTTP servers is fundamental for building web applications, APIs, and backend services with Node.js for modern web development.
As the creator of CoreUI, a widely used open-source UI library, I’ve built numerous Node.js servers to support CoreUI demos, documentation sites, and enterprise backend services.
From my expertise, the most straightforward approach is to use Node.js’s built-in http
module with createServer()
method.
This method provides direct control over request handling and is perfect for understanding server fundamentals before moving to frameworks like Express.
Use Node.js built-in http
module with createServer()
to create a basic HTTP server.
const http = require('http')
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('Hello World')
})
server.listen(3000, () => console.log('Server running on port 3000'))
The http.createServer()
method creates an HTTP server instance that listens for incoming requests. The callback function receives request
and response
objects for each HTTP request. res.writeHead()
sets the status code and headers, while res.end()
sends the response body and closes the connection. The server.listen()
method starts the server on the specified port, making it accessible via browser or HTTP clients.
Best Practice Note:
This is the same foundation we use for CoreUI backend services before adding Express framework layers. For production applications, consider using Express.js which provides middleware, routing, and additional features built on top of the http module.