0
0
ExpressHow-ToBeginner · 3 min read

How to Install Express.js: Step-by-Step Guide

To install express.js, first make sure you have Node.js installed. Then run npm install express in your project folder to add Express as a dependency.
📐

Syntax

Use the Node.js package manager npm to install Express.js in your project folder.

  • npm install express: Installs Express locally in your project.
  • npm install -g express: Installs Express globally (not recommended for projects).
bash
npm install express
💻

Example

This example shows how to install Express and create a simple server that responds with 'Hello World!'.

bash and javascript
npm init -y
npm install express

// Create a file named app.js with this content:
import express from 'express';
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Output
Server running at http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when installing Express.js include:

  • Not running npm install express inside your project folder.
  • Trying to use require syntax without enabling CommonJS or using older Node.js versions.
  • Forgetting to initialize your project with npm init before installing packages.

Always use import syntax with modern Node.js or configure your project for CommonJS if needed.

javascript
/* Wrong: Using require without setup */
const express = require('express'); // May cause error if using ES modules

/* Right: Using import syntax */
import express from 'express';
📊

Quick Reference

Tips for installing Express.js:

  • Run npm init -y once to create package.json.
  • Use npm install express to add Express locally.
  • Use import express from 'express' in your code with Node.js 14+.
  • Start your server with node app.js.

Key Takeaways

Install Express.js locally using npm with the command 'npm install express'.
Always initialize your project with 'npm init' before installing packages.
Use modern ES module syntax 'import express from "express"' in your code.
Run your Express app with 'node app.js' after installation.
Avoid installing Express globally; keep it as a project dependency.