Express.js Basic App

Creating a basic Express.js application is the first step toward mastering backend development with JavaScript. Express is the industry-standard "unopinionated" framework for Node.js, meaning it provides a robust set of features for web and mobile applications without forcing a specific project structure on you. Below is a step-by-step guide to building a functional web server that handles HTTP requests and returns responses.

Developer Tip: Express is often referred to as the "E" in the MERN, MEAN, and MEVN stacks. Learning it opens doors to building full-stack applications using MongoDB, React, Vue, or Angular.

 

Key Features of a Basic Express App

  • Handles HTTP requests: Express makes routing straightforward. It listens for specific methods (GET, POST, PUT, DELETE) at specific URLs and executes code in response.
  • Minimal setup: Unlike some "heavy" frameworks, Express stays out of your way. You only need a few lines of code to have a production-ready server running.
  • Middleware support: This is the "secret sauce" of Express. Middleware functions allow you to execute code, change the request/response objects, or end the request-response cycle entirely.
Best Practice: Always keep your route logic separate from your business logic as your app grows. For this basic tutorial, we'll keep them together, but in larger apps, use the Express Router.

 

Steps to Create a Basic Express App

Set up a New Node.js Project
Before writing any code, you need a package.json file to manage your project's metadata and dependencies. Initialize it by running the following command in your terminal:

npm init -y
Developer Tip: The -y flag tells npm to skip the setup questionnaire and use default values. You can always edit the package.json file later to add a description or change the version.

Install Express
Now, add Express to your project. This downloads the framework into a node_modules folder and updates your dependency list:

npm install express --save
Watch Out: Ensure you are running these commands inside your project folder. If you see an error about npm not being found, make sure Node.js is installed on your system.

Create the Application File
Create a file called app.js in your project directory. This will be the entry point for your server. Copy and paste the following code, then read the explanations below:

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

// Define a route for the home page
app.get('/', (req, res) => {
    res.send('Welcome to Express!');
});

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

// Set the application to listen on port 3000
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Code Breakdown:

  • const app = express();: This creates an instance of an Express application.
  • req (Request): Contains information about the incoming web request (headers, query parameters, etc.).
  • res (Response): Used to send data back to the client. res.send() automatically sets the correct Content-Type header for you.
Common Mistake: Forgetting to call a response method like res.send(), res.json(), or res.end(). If you don't respond, the browser will keep spinning until the request times out.

Run the Application
To start your server, execute the following command in your terminal:

node app.js

You should see the message Server is running on port 3000. This means your computer is now acting as a local web server!

Test the Routes
Open your web browser and navigate to the following addresses to see your app in action:

  • http://localhost:3000/: You will see "Welcome to Express!"
  • http://localhost:3000/about: You will see "This is the About page"
Developer Tip: Tired of restarting the server every time you make a change? Use Nodemon. Install it via npm install -g nodemon and run your app with nodemon app.js. It will auto-restart whenever you save a file.

Optional: Add Middleware for Logging
In real-world apps, you need to know who is accessing your site. Middleware acts as a "bridge" that runs before your route handler. Add this block above your route definitions:

app.use((req, res, next) => {
    console.log(`${new Date().toISOString()} - ${req.method} request to ${req.url}`);
    next(); // Pass control to the next middleware or route
});
Watch Out: If you forget to call next(), the request will hang and the route handlers below it will never execute.

 

Summary

Building a basic Express.js app is a straightforward process: initialize your project, install the package, define your routes, and start the listener. This minimal structure is incredibly powerful; it can be expanded into a REST API that serves JSON to a mobile app, or a full website that renders dynamic HTML. As you grow, you'll explore more advanced features like template engines, database integration, and security headers, but the core fundamentals remain the same.