Skip to main content

Express Installation

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. In this guide, we'll walk through the process of installing Express and setting up your first Express application.

Prerequisites

Before installing Express, make sure you have:

  • Node.js installed (version 10.x or later recommended)
  • npm (Node Package Manager) which comes with Node.js
  • Basic knowledge of JavaScript and terminal/command line usage

You can check if Node.js and npm are installed by running these commands in your terminal:

bash
node -v
npm -v

If they're not installed, download and install Node.js from nodejs.org.

Creating a New Express Project

Step 1: Create a Project Directory

First, create a new directory for your project and navigate into it:

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

Step 2: Initialize a Node.js Project

Initialize a new Node.js project by running:

bash
npm init

This will prompt you to enter information about your project. You can press Enter to accept the default values or provide custom information.

For a quicker setup, you can use:

bash
npm init -y

This creates a package.json file with default values.

Step 3: Install Express

Now, install Express as a dependency:

bash
npm install express

This command adds Express to your project dependencies in the package.json file and creates a node_modules directory containing the Express package and its dependencies.

Creating Your First Express Application

Let's create a simple Express server to ensure everything is installed correctly.

Step 1: Create an Entry Point File

Create a file named app.js or index.js in your project root:

bash
touch app.js

Step 2: Write Basic Express Code

Open app.js in your code editor and add the following code:

javascript
// Import the express module
const express = require('express');

// Create an Express application
const app = express();

// Define a port
const PORT = process.env.PORT || 3000;

// Create a route for the app root
app.get('/', (req, res) => {
res.send('Hello World! Welcome to my Express application.');
});

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

Step 3: Run Your Application

Start your Express server:

bash
node app.js

If everything is set up correctly, you should see "Server is running on port 3000" in your terminal.

Open your browser and navigate to http://localhost:3000. You should see "Hello World! Welcome to my Express application." displayed on the page.

Adding Express to an Existing Project

If you already have a Node.js project and want to add Express to it, navigate to your project directory and run:

bash
npm install express

Then, you can create or modify your entry point file as shown in the previous section.

Using Express Generator (Optional)

Express Generator is a command-line tool that quickly generates an Express application skeleton. This can be helpful for beginners to understand the structure of a more complete Express application.

Step 1: Install Express Generator

Install Express Generator globally:

bash
npm install -g express-generator

Step 2: Generate an Express Application

Create a new Express application with the default template:

bash
express my-new-app

Or specify a template engine (like Pug):

bash
express --view=pug my-new-app

Step 3: Install Dependencies and Run

Navigate to your new application directory and install dependencies:

bash
cd my-new-app
npm install

Start your application:

bash
npm start

By default, Express Generator creates a server running on port 3000. Access it by going to http://localhost:3000 in your browser.

Project Structure

After installing Express, your basic project structure will look like this:

my-express-app/
├── node_modules/ # Contains all installed packages
├── package.json # Project configuration and dependencies
├── package-lock.json # Exact dependency tree information
└── app.js # Main application file

If you used Express Generator, your project will have a more comprehensive structure:

my-new-app/
├── bin/ # Contains the startup script
├── node_modules/ # Contains all installed packages
├── public/ # Static files (CSS, JS, images)
├── routes/ # Route definitions
├── views/ # Templates for your views
├── app.js # Application setup
├── package.json # Project configuration and dependencies
└── package-lock.json # Exact dependency tree information

Real-World Application Example

Let's create a slightly more complex example with multiple routes and middleware:

javascript
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

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

// Middleware for URL-encoded bodies
app.use(express.urlencoded({ extended: true }));

// Middleware to serve static files
app.use(express.static('public'));

// Custom middleware
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} request to ${req.url}`);
next();
});

// Define routes
app.get('/', (req, res) => {
res.send('Welcome to the homepage');
});

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

// API route example
app.get('/api/users', (req, res) => {
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
res.json(users);
});

// POST example
app.post('/api/users', (req, res) => {
const newUser = req.body;
// In a real application, you would save this to a database
console.log('Created new user:', newUser);
res.status(201).json({
message: 'User created successfully',
user: newUser
});
});

// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});

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

To test this application:

  1. Create the file as shown above
  2. Run it with node app.js
  3. Access the different routes in your browser
  4. For the POST route, you can use tools like Postman or curl:
bash
curl -X POST -H "Content-Type: application/json" -d '{"name":"David"}' http://localhost:3000/api/users

Adding Dependencies for Common Tasks

Express is minimalist by design. For many common tasks, you'll want to install additional packages:

bash
# For environment variables
npm install dotenv

# For session management
npm install express-session

# For user authentication
npm install passport

# For database connectivity (MongoDB example)
npm install mongoose

# For security
npm install helmet

Summary

In this guide, you've learned:

  • How to set up a new Express project
  • Creating your first Express server
  • Using Express Generator for quick project scaffolding
  • Understanding the basic Express project structure
  • Creating a real-world Express application with multiple routes and middleware

Express.js provides an excellent foundation for building web applications with Node.js. Its minimalist approach gives you the flexibility to structure your application as you see fit while providing the essential tools for handling HTTP requests and responses.

Additional Resources

Practice Exercises

  1. Create a new Express application that serves an HTML file from a public directory.
  2. Add routes for a simple CRUD (Create, Read, Update, Delete) API for a resource of your choice.
  3. Implement middleware that logs all incoming requests to a file instead of the console.
  4. Create a route that accepts query parameters and returns them as part of the response.
  5. Build a simple form submission handler that processes form data and displays it back to the user.

Start with these exercises to strengthen your understanding of Express fundamentals, and gradually expand your skills by building more complex applications!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)