Node.js and Express have become the go-to tools for building fast, scalable web servers and APIs. If you’re new to backend development or want to learn how to create a simple server from scratch, this guide will walk you through the process step-by-step. By the end, you’ll have a running Express server that handles basic routes and serves responses.

What Is Node.js and Express?

Node.js is a JavaScript runtime that allows you to run JavaScript code outside the browser, on your computer or server. It’s built on Chrome’s V8 engine and is event-driven, making it ideal for building efficient network applications.

Express is a minimalist web framework built on top of Node.js. It simplifies building web servers by providing helpful methods to define routes, handle requests, and manage middleware.

Step 1: Install Node.js

Before starting, ensure Node.js is installed on your machine.

  • Go to nodejs.org and download the latest LTS (Long Term Support) version for your OS.
  • After installation, open a terminal or command prompt and check the installation by running:
node -v
npm -v

These commands display the installed Node.js and npm (Node Package Manager) versions.

Step 2: Initialize a New Project

Create a folder for your project and initialize it as a Node.js project:

mkdir my-express-server
cd my-express-server
npm init -y

The npm init -y command creates a default package.json file that manages your project’s dependencies and metadata.

Step 3: Install Express

Install Express using npm:

npm install express

This downloads and saves Express in your project’s node_modules folder and updates package.json.

Step 4: Create the Server File

Create a new file named index.js in your project folder. This file will hold the server code.

Step 5: Write the Express Server Code

Open index.js in your favorite text editor and add the following code:

const express = require('express');
const app = express();
const PORT = 3000;

// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world! This is my first Express server.');
});

// Define another route
app.get('/about', (req, res) => {
res.send('This is the about page.');
});

// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

Explanation:

  • We import Express and create an instance called app.
  • We define routes with app.get(). The first parameter is the URL path, the second is a callback function with request and response objects.
  • The server listens on port 3000, and when it starts, it logs a message.

Step 6: Run the Server

Go back to your terminal and run:

bashCopyEditnode index.js

You should see the message:
Server is running on http://localhost:3000

Open your browser and visit http://localhost:3000 — you’ll see “Hello, world! This is my first Express server.” Visit http://localhost:3000/about to see the about page message.

Step 7: Add JSON Response and Middleware

Express can also send JSON data and use middleware to handle requests.

Update your index.js like this:

app.use(express.json()); // Middleware to parse JSON bodies

app.post('/data', (req, res) => {
const userData = req.body;
res.json({
message: 'Data received successfully!',
yourData: userData
});
});

Now, your server can accept POST requests with JSON data at /data. You can test this with tools like Postman or curl.

Step 8: Handling 404 Errors

Add a fallback route at the bottom of your index.js file to handle requests to unknown routes:

app.use((req, res) => {
res.status(404).send('404: Page Not Found');
});

Step 9: Using Nodemon for Development

Instead of restarting the server manually after every change, you can use nodemon.

Install nodemon globally:

npm install -g nodemon

Run your server with nodemon:

nodemon index.js

Now, the server will auto-restart on file changes.

Conclusion

You’ve now built a basic Node.js server using Express that serves routes, handles JSON, and manages errors. This foundation lets you build more complex applications like REST APIs, web apps, or real-time services.

From here, consider learning about:

  • Routing parameters and query strings
  • Middleware for authentication and logging
  • Connecting to databases like MongoDB or MySQL
  • Deploying your server online with services like Heroku or Vercel

Node.js and Express offer incredible flexibility and speed for backend development — with this guide, you’re off to a great start.

Leave a Reply

Your email address will not be published. Required fields are marked *