Skip to content

02 - How to Build a Simple Web Server Using Node.js and Express.js: A Beginner-Friendly Guide

Published: at 11:00 am

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?

Prerequisites

Before starting, ensure the following:

Installing Dependencies

Step 1: Initialize a New Node.js Project

  1. Open your terminal and create a project folder:
    mkdir my-express-server
    cd my-express-server
    
  2. Initialize the project:
    npm init -y
    
    This generates a 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

Step 2: Start Postman

Step 3: Set Up a Request

Step 4: Send the Request

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

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

  1. Create a folder named public.
  2. Place your static files (e.g., index.html) inside.
  3. 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.

  1. 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
      
  2. Set Up a Render Account:

    • Go to Render and sign up or log in.
    • Click on “New +” and select “Web Service”.
  3. Connect Your Repository:

    • Link your GitHub or GitLab account to Render.
    • Select your project repository.
  4. 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}`);
        });
        
  5. 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

Stay tuned for more tutorials to enhance your backend development skills!


Previous Post
03 - Enhance Your Node.js Server: Routing, Middleware, and Database Integration
Next Post
01 - Introduction to Node.js: What It Is, Why You Need It, and When to Use It