Express.js โ€” Web APIs & middleware Study Material

Creating the app

Installation

1. Environment Verification


Before building, you must ensure the Runtime (Node) and the Package Manager (NPM) are stable.

  • Node.js is the "engine" that executes your code.

  • NPM is the "librarian" that fetches code written by others.


node -v # Check if the engine is ready
npm -v  # Check if the librarian is ready

2. Project Initialization


The Manifest (package.json)

Every Node project needs a identity. The package.json acts as the source of truth. It lists your project's version, scripts, and every single library required to make the app work. This allows other developers to run npm install and get the exact same setup as you.


The package-lock.json file is a deterministic manifest that records the exact version, location, and integrity of every dependency in your project's entire tree and it contains transitive dependencies information


mkdir my-app && cd my-app
npm init -y # The '-y' flag skips the questionnaire and uses defaults



3. Dependency Injection


Instead of writing a web server from scratch (which involves complex TCP/IP handling), we inject Express.

  • Production Dependencies: Essential for the app to run (Express, Dotenv).

  • Development Dependencies: Tools that make the developer's life easier but aren't needed by the end-user (Nodemon).


npm install express dotenv
npm install --save-dev nodemon


4. The Configuration Layer (.env)


The Theory: Security & Flexibility


You should never hardcode values like PORT = 3000.

  • Theory of Environments: In your local machine, the port might be 3000, but on your AWS EC2 instance, it might be 8080.

  • Dotenv allows the code to remain "environment agnostic"โ€”the code stays the same, while the variables change based on where the app is running.



The Process

Create a .env file:


PORT=5000


5. The "Watchdog" Setup (Nodemon)


By default, Node.js starts a process and "sticks" to the code it read at the start. It does not look at the files again.

  • Nodemon operates on a File System Watcher theory. It sits outside your code and monitors file changes. When you save, it kills the old Node process and starts a fresh one.

The Process

In package.json, add this script:


"scripts": {
  "dev": "nodemon src/app.js"
}


6. The Entry Point (app.js)


The Theory: The Request-Response Cycle

The entry point defines the "Pipeline."

  1. Instantiation: Creating the app object.

  2. Middleware: Using app.use() to process data before it hits your logic (e.g., parsing JSON).

  3. Binding: Telling the app to listen on a specific Port.


require('dotenv').config();
const express = require('express');
const app = express();

app.use(express.json()); // Middleware Theory: Data transformation

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server live on ${PORT}`));