Open In App

Creating a Simple HTTP Server in Node

Last Updated : 08 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers.It handles incoming requests from clients (typically web browsers), processes them, and sends back appropriate responses.

Steps to Create a NodeJS Server

To create a simple HTTP server in NodeJS, follow these steps:

Step 1: Initialize the Project

Begin by initializing your project using npm, which will create a package.json file to manage your project's dependencies and configurations.

npm init -y

Step 2: Import the HTTP Module

NodeJS includes a built-in HTTP module that allows you to create an HTTP server.

const http = require('http');

Step 3: Create a Server

Use the http.createServer() method to create an HTTP server. This method accepts a callback function that handles incoming requests and sends responses.

const server = http.createServer((request, response) => {
// Request handling logic
});

Step 4: Handle Requests

Within the server, set the response header and body to define how the server responds to incoming requests.

const server = http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('Hello, World!\n');
});

Example: After implementing the above steps, we will effectively establish the NodeJS server

JavaScript
const http = require('http');
const server = http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello, GeeksforGeeks!\n');
});
const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});
  • Loading the http Module: The http module is required to create an HTTP server.
  • Creating the Server: The createServer method is used to create the server, which takes a callback function that handles incoming requests and sends responses.
  • Setting Response Headers and Body: The writeHead method sets the HTTP status code and headers, while the end method sends the response body.
  • Starting the Server: The listen method starts the server on the specified port and IP address, and a callback function logs a message when the server is running.

Terminal Output: When you start the server, you'll see:

Terminal output
output

Web Browser Output: When you access http://localhost:3000/ in your web browser, the server responds with

Web Browser output
Create a Simple HTTP Server in Node

Now a simple HTTP server is created. You can enhance it to handle more complex use cases like CRUD operations etc.