Building a web server is an essential skill for modern web developers. Node.js and Express.js offer an efficient way to create scalable, high-performance web servers.
This tutorial will guide you step-by-step to set up your first server, even if you’re new to backend development.
Table of contents
Open Table of contents
Introduction
A web server is a software that processes requests from clients and delivers responses, often in the form of web pages. Using Node.js, a runtime environment for JavaScript, along with Express.js, a minimalist web framework, simplifies web server development.
Why Use Express.js?
- Simplifies HTTP server creation.
- Offers a clean structure for routes and middleware.
- Widely supported with extensive community resources.
Prerequisites
Before starting, ensure the following:
- Node.js and npm are installed. Download Node.js here.
- A basic understanding of JavaScript.
- A code editor like Visual Studio Code
- Postman (optional): A powerful tool to test APIs and HTTP requests.
Installing Dependencies
Step 1: Initialize a New Node.js Project
- Open your terminal and create a project folder:
mkdir my-express-server cd my-express-server
- Initialize the project:
This generates anpm init -y
package.json
file with default settings.
Step 2: Install Express.js
Run the following command to install Express.js:
npm install express
Creating Your First Express.js Server
Step 1: Write the Server Code
Create a file named server.js
and add the following code:
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.send("Hello, World!");
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 2: Start the Server
Run the server using:
node server.js
Visit http://localhost:3000
in your browser to see the message “Hello, World!”
Testing with Postman
Postman is an excellent tool for testing APIs. Here’s how you can use it:
Step 1: Download and Install Postman
- Visit the Postman website and download the app for your operating system.
Step 2: Start Postman
- Open Postman and click on Create a New Request.
Step 3: Set Up a Request
- Choose GET as the HTTP method.
- Enter http://localhost:3000 in the request URL field.
Step 4: Send the Request
- Click on Send.
- The response should display “Hello, World!” in the response section.
You can use Postman to test other endpoints and HTTP methods (e.g., POST, PUT, DELETE) as you build your server.
Handling HTTP Requests
Express.js allows you to handle different HTTP methods with ease.
Example: Handling GET and POST Requests
app.get("/about", (req, res) => {
res.send("About Page");
});
app.post("/data", (req, res) => {
res.send("Data received");
});
Exploring req
and res
Objects
req
: Contains information about the client’s request.res
: Used to send a response back to the client.
Adding Middleware
Middleware functions process requests before sending responses. They’re essential for logging, parsing, and handling errors.
Example: Adding Built-In Middleware
app.use(express.json()); // Parses incoming JSON requests
Custom Middleware
app.use((req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next();
});
Serving Static Files
To serve files like HTML, CSS, and JavaScript:
Example: Setting Up Static Files
- Create a folder named
public
. - Place your static files (e.g.,
index.html
) inside. - Use the following code:
app.use(express.static("public"));
Visit http://localhost:3000/index.html
to view your static file.
Error Handling
Handling errors improves user experience.
404 Error Route
app.use((req, res) => {
res.status(404).send("Page Not Found");
});
Error-Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something went wrong!");
});
Deploying Your Web Server
To make your server accessible online, deploy it using platforms like Render.
Steps for Deployment on Render
Render is a modern cloud platform that offers easy deployment for web applications.
-
Create a Git Repository:
- If you haven’t already, initialize a Git repository for your project:
git init git add . git commit -m "Initial commit"
- Push your code to a Git hosting platform like GitHub or GitLab:
git remote add origin <repository-url> git push -u origin main
- If you haven’t already, initialize a Git repository for your project:
-
Set Up a Render Account:
- Go to Render and sign up or log in.
- Click on “New +” and select “Web Service”.
-
Connect Your Repository:
- Link your GitHub or GitLab account to Render.
- Select your project repository.
-
Configure the Deployment:
- Fill in the required details:
- Name: Give your service a name.
- Environment: Choose
Node
as the runtime. - Build Command: Leave it as default (
npm install
). - Start Command: Use:
node server.js
- Port: Render automatically assigns a port, so ensure your server uses
process.env.PORT
(update your server file if needed):const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
- Fill in the required details:
-
Deploy the Server:
- Click on “Create Web Service.”
- Render will build and deploy your application. Once complete, you’ll receive a live URL to access your server.
Testing the Deployment
Open the provided URL in a browser. You should see your application live, serving responses just like it did locally.
Conclusion and Next Steps
You’ve successfully built a web server using Node.js and Express.js!
Next Steps
- Experiment with environment variables for secure configurations.
- Integrate a database (e.g., MongoDB or PostgreSQL) for data persistence.
- Enhance your app with user authentication, authorization, and advanced routing features.
Stay tuned for more tutorials to enhance your backend development skills!