Skip to main content

Express Environment Setup

Before you can start building web applications with Express.js, you need to set up your development environment. This guide will walk you through all the necessary steps to get your environment ready for Express development, from installing Node.js to creating your first Express application.

Prerequisites

To work with Express.js, you'll need:

  • A computer with internet access
  • Basic familiarity with command-line interfaces
  • A text editor or IDE (like Visual Studio Code, Sublime Text, or Atom)

Installing Node.js and npm

Express.js is a framework built on Node.js, so your first step is to install Node.js, which comes bundled with npm (Node Package Manager).

Step 1: Download and Install Node.js

  1. Visit the official Node.js website
  2. Download the LTS (Long Term Support) version, which is recommended for most users
  3. Run the installer and follow the installation instructions for your operating system

Step 2: Verify Installation

After installation, verify that Node.js and npm are correctly installed by opening your terminal or command prompt and running:

bash
node --version
npm --version

You should see version numbers for both, similar to:

v16.15.1
8.11.0

If you see version numbers, congratulations! Node.js and npm are successfully installed.

Creating a New Express Project

Now that you have Node.js and npm installed, let's create a new Express project.

Step 1: Create a Project Directory

First, create a directory for your new 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 creating a package.json file:

bash
npm init -y

The -y flag accepts all default settings. Your output should look similar to:

Wrote to /path/to/my-express-app/package.json:

{
"name": "my-express-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

Step 3: Install Express

Now, install Express as a dependency for your project:

bash
npm install express

You should see output indicating that Express and its dependencies are being installed:

added 57 packages, and audited 58 packages in 3s

7 packages are looking for funding
run `npm fund` for details

found 0 vulnerabilities

Creating Your First Express Application

Let's create a simple Express application to ensure everything is working correctly.

Step 1: Create an Index File

Create a file named index.js in your project directory:

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

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

// Define a port
const port = 3000;

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

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

Step 2: Run Your Application

Start your Express application by running:

bash
node index.js

You should see the following output:

Server running at http://localhost:3000/

Step 3: Test Your Application

Open your web browser and navigate to http://localhost:3000/. You should see:

Hello World! Welcome to my Express application.

Congratulations! You've successfully set up your Express environment and created your first application.

Improving Your Development Workflow

While the basic setup works, let's add some tools to improve your development workflow.

Installing Nodemon for Automatic Restarts

During development, you'll make frequent changes to your code. Instead of manually restarting the server after each change, you can use Nodemon to automatically restart your server when files change.

bash
npm install --save-dev nodemon

Update your package.json file by adding the following to the scripts section:

json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js",
"dev": "nodemon index.js"
}

Now you can run your application with automatic restarts using:

bash
npm run dev

Project Structure Best Practices

As your Express application grows, organizing your code becomes increasingly important. Here's a recommended project structure:

my-express-app/
├── node_modules/
├── public/ # Static files (CSS, images, client-side JS)
├── routes/ # Route handlers
│ ├── index.js
│ └── users.js
├── views/ # Templates (if using a template engine)
├── controllers/ # Controllers that handle request logic
├── models/ # Data models
├── middleware/ # Custom middleware
├── config/ # Configuration files
├── .gitignore # Git ignore file
├── package.json
├── package-lock.json
└── index.js # Application entry point

You can create this structure as your application grows:

bash
mkdir -p public routes views controllers models middleware config

Environment Variables and Configuration

For secure and flexible configuration, use environment variables:

  1. Install dotenv:
bash
npm install dotenv
  1. Create a .env file in your project root:
PORT=3000
NODE_ENV=development
# Add other configuration variables here
  1. Add .env to your .gitignore file to avoid committing sensitive information:
node_modules/
.env
  1. Update your index.js to use environment variables:
javascript
// Load environment variables
require('dotenv').config();

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

// Use the PORT from environment variables or default to 3000
const port = process.env.PORT || 3000;

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

app.listen(port, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${port}`);
});

Summary

In this guide, you've learned how to:

  • Install Node.js and npm
  • Create a new Express project
  • Install Express and create a simple application
  • Improve your development workflow with Nodemon
  • Structure your project following best practices
  • Configure your application using environment variables

Your Express environment is now set up and ready for development. With these fundamentals in place, you can start building more complex web applications using Express.js.

Additional Resources

Exercises

  1. Create a new Express application with two routes: /about and /contact.
  2. Modify your Express application to serve static files from a public directory.
  3. Create a route that returns JSON data instead of plain text.
  4. Set up environment variables for different configurations in development and production.
  5. Create a middleware that logs all incoming requests to your Express application.

Happy coding!



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