Introduction

Node.js is a powerful runtime for executing JavaScript outside the browser. It allows developers to build scalable, fast, and efficient server-side applications. Express.js, a lightweight and flexible Node.js framework, simplifies the process of building web applications and APIs.

In this guide, we’ll walk you through setting up a basic Node.js application using Express, covering installation, project setup, routing, middleware, and running the server.


1. Prerequisites

Before we begin, ensure you have the following installed on your system:

  • Node.js (Download from nodejs.org)
  • npm (Node Package Manager) (Comes with Node.js)
  • A text editor (e.g., VS Code)
  • A terminal or command prompt

To check if Node.js and npm are installed, run:

node -v  # Check Node.js version
npm -v   # Check npm version

2. Setting Up a New Node.js Project

Step 1: Create a Project Directory

Navigate to the folder where you want to create your project and run:

mkdir my-express-app
cd my-express-app

Step 2: Initialize a Node.js Project

Run the following command to initialize a new Node.js project:

npm init -y

This will create a package.json file with default settings.


3. Installing Express.js

To install Express, run:

npm install express

This adds Express as a dependency in the package.json file.


4. Creating a Basic Express Server

Step 1: Create an index.js File

Inside the project folder, create a new file named index.js and open it in your editor.

Step 2: Add the Following Code

const express = require('express');  // Import Express
const app = express();  // Create an Express app

const PORT = 3000;  // Define the port

// Define a simple route
app.get('/', (req, res) => {
    res.send('Hello, World! Welcome to Express.js');
});

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

5. Running the Express Server

Save the file and run the following command in the terminal:

node index.js

You should see this output:

Server is running on http://localhost:3000

Open your browser and go to http://localhost:3000. You should see the message “Hello, World! Welcome to Express.js” displayed.


6. Understanding Routes in Express

Routes define how an application responds to client requests.

Adding More Routes

Modify index.js to include more routes:

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

app.get('/contact', (req, res) => {
    res.send('Contact us at: [email protected]');
});

Now, you can visit:


7. Handling Request Parameters and Query Strings

Route Parameters

Example of dynamic URL parameters:

app.get('/user/:name', (req, res) => {
    res.send(`Welcome, ${req.params.name}!`);
});

Visiting http://localhost:3000/user/John will display:

Welcome, John!

Query Strings

Access query parameters using req.query:

app.get('/search', (req, res) => {
    let query = req.query.q;
    res.send(`You searched for: ${query}`);
});

Visiting http://localhost:3000/search?q=express will display:

You searched for: express

8. Using Middleware in Express

Logging Middleware

Create a simple logger middleware:

app.use((req, res, next) => {
    console.log(`Request Method: ${req.method}, Request URL: ${req.url}`);
    next();  // Move to the next middleware or route
});

Serving Static Files

To serve static files (like images, CSS, JavaScript), use express.static():

app.use(express.static('public'));

Create a public folder in your project and add a file like public/index.html.


9. Handling Form Data in Express

To process form data, install body-parser:

npm install body-parser

Then, update index.js:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
    res.send(`Received data: ${req.body.name}`);
});

Now, posting data to /submit will process form inputs.


10. Handling Errors in Express

Use a middleware function to handle errors:

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something went wrong!');
});

11. Using Nodemon for Auto-Restart

Install nodemon:

npm install -g nodemon

Run the server with:

nodemon index.js

Now, it automatically restarts on file changes.


12. Deploying Your Express App

You can deploy on:

  • Heroku
  • Vercel
  • Render
  • DigitalOcean

Example steps for deploying on Heroku:

npm install -g heroku
heroku login
git init
heroku create
git add .
git commit -m "Deploy Express App"
git push heroku master

Conclusion

Congratulations! 🎉 You’ve built a basic Express.js application, learned about routing, middleware, error handling, and deployment.

Next Steps

  • Connect Express with MongoDB (using Mongoose).
  • Implement JWT authentication.
  • Build a REST API with Express & MongoDB.

Start experimenting and build something amazing with Express.js! 🚀