Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node JS Versions
Next article icon

Node.js Web Server

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A NodeJS web server is a server built using NodeJS to handle HTTP requests and responses. Unlike traditional web servers like Apache or Nginx, which are primarily designed to give static content, NodeJS web servers can handle both static and dynamic content while supporting real-time communication. It uses JavaScript (the same language used for client-side scripting) on the server side, making it a popular choice for full-stack developers.

Setting Up a NodeJS Web Server

Step 1: Install NodeJS

If you haven’t installed NodeJS in your system, follow the article- How to Install NodeJS

To verify the installation, open your terminal or command prompt and type:

node -v

This will display the installed NodeJS version.

Step 2: Create Your Project Directory

Create a new directory for your project and navigate into it:

mkdir node-server cd node-server

Step 3: Initialize the Project

Create a package.json file, which contains metadata about your project:

npm init -y

Step 4: Create a Basic Server

Create a file named server.js

Open server.js in your code editor and add the following code to create a simple HTTP server:

JavaScript
const http = require('http');  const server = http.createServer((req, res) => {     res.writeHead(200, { 'Content-Type': 'text/plain' });     res.end('Hello, World!'); });  const port = 3000; const host = 'localhost';  server.listen(port, host, () => {     console.log(`Server running at http://${host}:${port}/`); }); 

Output

Run the server by using the below command

node server.js
Screenshot-2025-03-05-151651

Web Server

In this example

  • http.createServer(): Creates an HTTP server that listens for requests.
  • res.writeHead(): Sends a response header with the status code 200 (OK).
  • res.end(): Ends the response and sends the message “Hello, World!” to the client.
  • server.listen(): Starts the server on the specified host (localhost) and port (3000).

Why Use NodeJS for Web Servers?

1. High Performance

NodeJS is designed for speed. Its non-blocking I/O model and the V8 engine allow for fast execution of JavaScript code, making it ideal for handling high-concurrency scenarios, such as APIs or real-time applications.

2. Single Language Stack

NodeJS enables developers to use JavaScript both on the client side and server side. This eliminates the need to switch between different programming languages and allows for better integration between the front-end and back-end.

3. Scalability

NodeJS is scalable by design due to its event-driven architecture. It can easily handle more requests with minimal overhead by adding more processes or utilizing a load balancer.

4. Real-Time Data

NodeJS is especially well-suited for applications that require real-time data, such as chat applications, live notifications, and collaborative platforms. Its WebSocket support allows for full-duplex communication between the client and server.

5. Large Ecosystem

NodeJS has an extensive ecosystem with over a million open-source libraries available through npm. These libraries make it easy to add functionality such as authentication, routing, data handling, and much more.

How Does a NodeJS Web Server Work?

  • Event Loop: The server listens for incoming requests and processes them in a non-blocking way. When a request comes in, it is passed to the event loop, which decides how to handle it.
  • Non-Blocking I/O: While the server is processing a request (like querying a database or reading from a file), it does not block other incoming requests. This is handled asynchronously through callbacks, promises, or async/await syntax.
  • Request and Response: Once the event loop processes the request, the server sends a response back to the client (browser, API consumer, etc.). The response could be in HTML, JSON, or other data format.
  • Web Servers: NodeJS can serve static files (like images or stylesheets) and dynamic content (like API responses) using built-in modules like http, fs, and path.

Routing in NodeJS Web Server

In real-world applications, your server needs to handle different routes (URLs) and respond differently based on the request. Let us understand with the help of the example:

JavaScript
// server.js  const http = require('http');  const hostname = '127.0.0.1'; const port = 3000;  const server = http.createServer((req, res) => {     if (req.url === '/') {         res.statusCode = 200;         res.setHeader('Content-Type', 'text/plain');         res.end('Welcome to the Homepage!');     } else if (req.url === '/about') {         res.statusCode = 200;         res.setHeader('Content-Type', 'text/plain');         res.end('This is the About Page');     } else if (req.url === '/contact') {         res.statusCode = 200;         res.setHeader('Content-Type', 'text/plain');         res.end('This is the Contact Us Page');     }     else {         res.statusCode = 404;         res.setHeader('Content-Type', 'text/plain');         res.end('Page Not Found');     } });  server.listen(port, hostname, () => {     console.log(`Server running at http://${hostname}:${port}/`); }); 

Output

In this example

  • The http.createServer() method initializes the server.
  • res.writeHead() sends a response header with the status code (e.g., 200 OK) and any other headers.
  • res.statusCode sets the HTTP status code for the response. In this case, 200 means the request was successful.
  • res.setHeader() sets the content type of the response. In this case, text/plain means the server is sending plain text back to the client.
  • server.listen() binds the server to the specified port and hostname (in this case, localhost:3000).
  • When the server successfully starts, the callback function is executed, logging a message (Server running at http://127.0.0.1:3000/) to the console.

Key Benefits of Using a NodeJS Web Server

  • Real-Time Capabilities: NodeJS can be used in the real-time applications like chat apps or live data streaming due to its non-blocking architecture and event-driven model.
  • High Performance: The V8 engine provides fast execution of JavaScript, making NodeJS a great choice for applications requiring high performance and low latency.
  • Scalability: NodeJS is highly scalable, thanks to its event loop and non-blocking I/O. It can handle a large number of simultaneous requests efficiently.
  • Lightweight and Efficient: With its single-threaded, non-blocking nature, NodeJS reduces the overhead of traditional multi-threaded servers, making it lightweight and ideal for handling concurrent requests.


Next Article
Node JS Versions

G

g_ragini
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Basics

Similar Reads

  • Web-Socket in Node
    WebSockets in Express.js and Node.js enable real-time, two-way communication between a website and its server. This allows for features like live chat, instant updates, and interactive experiences. WebSockets maintain a persistent connection, unlike typical web requests.Libraries such as ws and sock
    5 min read
  • How to Run Node Server?
    A Node server runs JavaScript outside the browser to handle web requests. It listens for incoming requests, processes them, and sends responses. Unlike traditional servers, it handles multiple requests at once without waiting for each to finish. Some of the key features of the Node Server are: Non-B
    3 min read
  • Node JS Versions
    Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applic
    5 min read
  • Next.js Custom Server
    Next.js Custom Server allows advanced customization by overriding default behavior. It enables tailored server-side logic, middleware integration, and API route handling, offering flexibility beyond standard Next.js configurations. Next.js Custom ServerA custom server in Next.js is a Node.js script
    3 min read
  • Node.js Projects
    Node.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
    9 min read
  • Node.js with TypeScript
    If you're immersed in the world of Node.js development, you're likely acquainted with the hurdles of handling and expanding a substantial codebase. A viable solution to tackle this is leveraging TypeScript, a statically-typed superset of JavaScript. TypeScript enriches the language with optional typ
    6 min read
  • Node.js http.server.setTimeout() Method
    The http.server.setTimeout() is an inbuilt application programming interface of the class Server within HTTP module which is used to set the time-out value for the socket. Syntax: server.setTimeout([msecs][, callback]) Parameters: This method takes the socket time-out value in a millisecond. Return
    3 min read
  • How To Start Next.js Server?
    Next.js is a React framework created by Vercel that helps developers build server-side rendered and static web applications. Starting a Next.js server is a simple process that allows you to see your application running in a local development environment or a production environment. PrerequisitesNode
    2 min read
  • How to Build a Simple Web Server with Node.js ?
    Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and it’s not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
    3 min read
  • How to Build a Node.js Proxy Server ?
    A proxy server acts as an intermediary between a client and other servers. It can be used for various purposes, including load balancing, security, and caching. In the context of web development, a proxy server forwards requests from clients to other servers, fetches responses, and sends them back t
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences