How to Create a Simple Server Using ExpressJS?
Last Updated :
25 Feb, 2025
The server plays an important role in the development of the web application. It helps in managing API requests and communication between the client and the backend. ExpressJS is the fast and famous framework of the Node.Js which is used for creating the server.
In this article, we will create a simple server using the ExpressJS.
What is the Server?
A server is a program that listens to client requests and responds with data, such as web pages or APIs. Servers are essential for hosting websites, handling user requests, and serving dynamic content.
ExpressJS simplifies server creation in Node.js by providing an easy-to-use API for handling requests, responses, and middleware
- Fast & Lightweight: Express makes building servers quick and efficient.
- Simplified Routing: Easily handle different URL paths and HTTP methods.
Steps to Create a Simple Server Using ExpressJS
Follow these steps to create a basic Express server with an HTML page.
Step 1: Create a Project Folder
Open your terminal or VS Code and create a new folder named root. Navigate inside it.
mkdir express-app
cd express-app
Step 2: Initialize a Node.js Project
Run the following command to create a package.json file, which manages dependencies.
npm init -y
Package.JsonStep 3: Install ExpressJS
Install Express as a dependency to set up your server.
npm i express
Dependencies:
"dependencies": {
"express": "^4.18.2",
}
Step 4: Create the Server File
Create a file named server.js in your project directory and add the following code
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('<h1>Hello, Geeks!</h1><p>This is your simple Express server.</p>');
});
app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});
Step 5: Start the Server
In the terminal, start your server with the following command:
node server.js
Output
Express Server- Import Express: Loads the Express module.
- Create an App Instance: Initializes the Express application.
- Define a Port: Sets the port number to 3000.
- Set Up a Route: Defines a route for the root URL (/) that sends an HTML response.
- Start the Server: Begins listening on the specified port and logs a message to the console.
Best Practices for Creating a Simple Server Using ExpressJS
- Use Environment Variables: Store configuration details like port numbers and database URLs in environment variables to enhance security and flexibility.
- Implement Error Handling: Use middleware to manage errors gracefully, ensuring the server remains stable and provides informative responses.
- Log Requests and Errors: Implement logging to monitor server activity and troubleshoot issues effectively.