Introduction to Express.js: Building Web Applications with Node.js

Your comprehensive starting point for learning Express.js, the de facto standard server framework for Node.js, in 2025.

1. What is Express.js?

Express.js, often simply called Express, is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It is designed for building single-page, multi-page, and hybrid web applications, as well as APIs.

Released in 2010, Express has become the most popular choice for backend development with Node.js due to its simplicity, unopinionated nature, and powerful features. It doesn't impose strict rules on how you structure your application, giving developers the freedom to organize their projects as they see fit. Think of it as a layer built on top of Node.js's http module, making it easier to handle requests, routing, middleware, and more.

This guide will introduce you to:

Whether you're a developer in Mirabel, Quebec, or anywhere else in the world, Express.js provides a solid foundation for your Node.js backend projects.

2. Why Choose Express.js? Key Advantages

Express.js offers several compelling reasons for its widespread adoption in the Node.js ecosystem:

Express.js: Fast, Unopinionated, Minimalist

Node.js Core (http module)
      ^
      |  Adds Structure & Utilities
      |
[ Express.js Framework ] --> Simplifies --> [ Web Apps & APIs ]
                

3. Core Concepts of Express.js

Understanding a few fundamental concepts is key to working effectively with Express.js.

3.1 Routing

Routing refers to how an application’s endpoints (URIs) respond to client requests. It involves defining how the application should handle requests to specific paths and HTTP methods.

In Express, you define routes using methods on the `app` object (an instance of Express) that correspond to HTTP methods. For example:

The `handler` is a function that Express calls when the route is matched. This function receives request (`req`) and response (`res`) objects.

3.2 Middleware

Middleware functions are functions that have access to the request object (`req`), the response object (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the next middleware in the stack.

Middleware can:

If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.

Common uses for middleware include logging, parsing request bodies, authentication, error handling, and serving static files.

3.3 Request (`req`) and Response (`res`) Objects

In every route handler and middleware function, Express provides two important objects:

Understanding how to use these objects is fundamental to building Express applications.

4. Getting Started: Setting Up Your Environment

Before you can start using Express.js, you need to have Node.js and npm (Node Package Manager) installed on your system. npm comes bundled with Node.js.

  1. Install Node.js and npm: If you haven't already, download and install Node.js from nodejs.org. This will also install npm.
  2. Create a Project Directory:
    mkdir my-express-app
    cd my-express-app
  3. Initialize Your Project: This creates a `package.json` file, which manages your project's dependencies and other metadata.
    npm init -y
    (The `-y` flag accepts all default settings).
  4. Install Express: Install Express.js as a project dependency.
    npm install express

Now you're ready to start building your Express application!

5. Your First Express.js Application ("Hello World")

Let's create a very simple Express application that starts a server and listens on port 3000 for connections. Create a file named `app.js` (or `index.js`) in your project directory:


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

// Define a route handler for GET requests to the root URL ('/')
app.get('/', (req, res) => {
  res.send('Hello World from Express.js!');
});

// Start the server and listen on the specified port
app.listen(port, () => {
  console.log(`Express app listening at http://localhost:${port}`);
});
            

To run this application:

node app.js

Now, if you open your web browser and navigate to `http://localhost:3000`, you should see "Hello World from Express.js!".

6. Basic Routing Examples

Let's expand on routing with a few more examples in your `app.js`:


// ... (previous setup code)

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

// POST request to /submit-data (you'd typically use a tool like Postman to test POST)
app.post('/submit-data', (req, res) => {
  res.send('Data submitted successfully! (POST request)');
});

// Route parameters: /users/:userId
app.get('/users/:userId', (req, res) => {
  res.send(`User Profile for User ID: ${req.params.userId}`);
});

// Query parameters: /search?q=express
app.get('/search', (req, res) => {
  const searchTerm = req.query.q;
  res.send(`Search results for: ${searchTerm}`);
});

// ... (app.listen code)
            

Restart your Node.js server to see these changes. You can test these routes in your browser or using a tool like Postman or curl.

7. Serving Static Files

Express can serve static files like HTML, CSS, images, and client-side JavaScript. The `express.static` built-in middleware is used for this.

Create a folder named `public` in your project root. Inside `public`, you can place files like `index.html`, `style.css`, etc.

Add this line to your `app.js` (usually before your route definitions):


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

Now, if you have an `index.html` in your `public` folder, it will be served when you visit `http://localhost:3000/`. If you have `public/css/style.css`, it will be accessible at `http://localhost:3000/css/style.css`.

8. Using Template Engines (Optional)

For rendering dynamic HTML content, Express can integrate with various template engines like Pug (formerly Jade), EJS, or Handlebars.

First, install your chosen template engine (e.g., EJS):

npm install ejs

Then, configure it in `app.js`:


// ...
// Set the view engine to ejs
app.set('view engine', 'ejs');
// Optionally, specify the directory for views (defaults to 'views' folder)
// app.set('views', path.join(__dirname, 'my-views-folder'));

app.get('/profile', (req, res) => {
  const userData = { name: 'Qwirey User', location: 'Mirabel, QC' };
  // Renders views/profile.ejs and passes data
  res.render('profile', { user: userData });
});
// ...
            

You would then create a file named `profile.ejs` in a `views` folder in your project root to display the dynamic data.

9. Basic Error Handling

Express has built-in error handling, and you can also define custom error-handling middleware.

An error-handling middleware function is defined in the same way as other middleware functions, except it has four arguments instead of three: `(err, req, res, next)`.


// ... (after all your app.use() and routes)

// Catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// Error handler middleware
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page or send error response
  res.status(err.status || 500);
  res.send(`Error: ${err.status || 500} - ${err.message}`); // Or render an error view
});
// ...
            

This is a basic setup. More sophisticated error handling can be implemented for production applications.

10. Next Steps & Conclusion

Building on the Basics

This guide has provided a foundational introduction to Express.js. You've learned what Express is, its core concepts, how to set it up, and how to build simple routes and serve content. Express.js is a powerful tool that simplifies backend development with Node.js, allowing you to build robust web applications and APIs efficiently.

From here, you can explore more advanced topics such as:

Key Resources for Further Learning:

Official Documentation & Guides:

Community & Tutorials:

  • Stack Overflow (for specific questions)
  • Dev.to, Medium, Smashing Magazine (for articles and tutorials)
  • Online learning platforms like Udemy, Coursera, freeCodeCamp.

References (Illustrative)

Key references include the official Express.js documentation.