Time to start the DevTinder backend. In this chapter you'll set up a Node.js project with npm, understand every file it creates, install Express, and write your first Express server, plus a tool that restarts it automatically while you code.
In this chapter you'll learn
- what
npm initdoes, and every important field inpackage.json - dependencies vs devDependencies, and version numbers like
^5.1.0 - what
node_modulesandpackage-lock.jsonare, and what goes in.gitignore - what Express is, and how to write a basic Express server
- how
app.use()matches routes, and why order matters - auto-restarting with
nodemonornode --watch, and global vs local installs
Before you start: read Chapter 11: Creating the Server (the http module). Code for the whole backend: DevTinder backend repository.
Step 1: Create the project with npm
npm (Node Package Manager) comes with Node.js (Chapter 01: Introduction to NodeJs). It creates projects, installs packages and runs scripts.
mkdir devTinder-backend
cd devTinder-backend
npm init # answers a few questions (name, version, entry point...)
# or: npm init -y to accept all defaultsmkdir devTinder-backend
cd devTinder-backend
npm init # answers a few questions (name, version, entry point...)
# or: npm init -y to accept all defaultsThis creates package.json, the project's identity card.
package.json, field by field
{
"name": "devtinder-backend",
"version": "1.0.0",
"description": "Backend for DevTinder",
"main": "src/app.js",
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
},
"dependencies": {
"express": "^5.1.0"
},
"devDependencies": {
"nodemon": "^3.1.10"
}
}{
"name": "devtinder-backend",
"version": "1.0.0",
"description": "Backend for DevTinder",
"main": "src/app.js",
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
},
"dependencies": {
"express": "^5.1.0"
},
"devDependencies": {
"nodemon": "^3.1.10"
}
}| Field | What it's for |
|---|---|
name, version, description | identify the project |
main | the entry file when someone requires this package |
scripts | shortcuts you run with npm run <name>: npm run dev. (start and test work without run: npm start) |
dependencies | packages your app needs to run in production (Express, Mongoose...) |
devDependencies | packages needed only while developing (nodemon, test tools, linters) |
type | "module" makes .js files ES Modules (Chapter 04: module.export & require); the course leaves it out, so files are CommonJS |
Version numbers: semantic versioning
Packages use semantic versioning (semver): MAJOR.MINOR.PATCH, for example 5.1.0.
- PATCH (
5.1.0 → 5.1.1): bug fixes only. - MINOR (
5.1.0 → 5.2.0): new features, nothing breaks. - MAJOR (
4.21.0 → 5.0.0): breaking changes; your code may need updating.
The symbol in front says which updates npm install may pick:
In package.json | Allows | Example |
|---|---|---|
^5.1.0 (caret, the default) | minor and patch updates | any 5.x.x ≥ 5.1.0 |
~5.1.0 (tilde) | patch updates only | 5.1.x |
5.1.0 | exactly this version | 5.1.0 |
Step 2: Install Express
npm install expressnpm install expressThree things happen:
- Express (and everything Express itself depends on) is downloaded into
node_modules/. "express": "^5.x.x"is added todependenciesinpackage.json.package-lock.jsonis created or updated.
npm install express now installs Express 5 (the default since 2025). The original lectures used Express 4. Almost everything in this course works the same in both; the differences that matter (route path syntax and async error handling) are pointed out in Chapter S2 04: Routing and Request handlers and Chapter S2 05: Middlewares and Error Handlers. To match the lectures exactly, install npm install express@4.
node_modules/
The folder where all installed packages live, including the packages your packages depend on (Express alone pulls in dozens). It can get large, but you never edit it and never commit it to Git: anyone can recreate it with npm install.
package-lock.json
package.json says "Express, any 5.x version". package-lock.json records the exact version of every package that was actually installed, including nested ones.
Why it matters: without it, you might install Express 5.1.0 today and your teammate 5.3.0 next month, getting different behaviour. With the lock file, everyone installs the same versions. Commit it to Git.
npm installinstalls frompackage.jsonand updates the lock file if needed.npm ciinstalls exactly what's in the lock file (and fails if it doesn't matchpackage.json). Use it on servers and in CI pipelines.
.gitignore
A file that tells Git which files not to track:
node_modules/
.envnode_modules/
.env.env holds secrets like your database password (Chapter S2 06: Database, Schema, Models & Mongoose). It must never reach GitHub.
Step 3: What is Express?
Express is a minimal web framework for Node.js. In Chapter 11: Creating the Server you built a server with the raw http module and wrote if (req.url === ...) chains by hand. Express does the repetitive parts for you:
- routing by method and path, including parameters like
/user/:id - middleware: reusable functions that run before your route handlers (Chapter S2 05: Middlewares and Error Handlers)
- helpers such as
res.send(),res.json(),res.status() - parsing JSON request bodies (
express.json()), query strings, and more
Under the hood, Express still uses http.createServer.
Step 4: Your first Express server
The course puts the code in src/app.js:
// src/app.js
const express = require("express");
const app = express(); // create an Express application
app.get("/test", (req, res) => {
res.send("Hello from the test route!");
});
app.get("/", (req, res) => {
res.send("Namaste from DevTinder!");
});
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});// src/app.js
const express = require("express");
const app = express(); // create an Express application
app.get("/test", (req, res) => {
res.send("Hello from the test route!");
});
app.get("/", (req, res) => {
res.send("Namaste from DevTinder!");
});
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});Run it with node src/app.js and open http://localhost:3000/test.
express()creates the app, the object you attach routes and middleware to.app.get(path, handler)handles GET requests to that exact path.- The handler
(req, res) => {}is called a request handler or route handler. Express gives it richer versions of thereqandresyou saw in Chapter 11: Creating the Server. res.send()sends a response and sets theContent-Typefor you (text, HTML or JSON, based on what you pass).app.listen(3000)starts the server, just likeserver.listenin Chapter 11: Creating the Server.
app.use() vs app.get(): matching and order
The lectures start with app.use(). It behaves differently from app.get():
app.use("/test", (req, res) => {
res.send("Hello from /test");
});app.use("/test", (req, res) => {
res.send("Hello from /test");
});app.use("/test", ...) matches:
- every HTTP method (GET, POST, DELETE...), not just GET
- every path that starts with
/testas a whole segment:/test,/test/abc,/test/abc/xyz, but not/testing
That makes app.use right for middleware (code that should run for many routes), but too broad for a normal endpoint. For endpoints, use the method-specific functions (app.get, app.post...).
Order matters
Express checks routes from top to bottom and uses the first one that matches and sends a response:
app.use("/", (req, res) => {
res.send("Catch-all!"); // "/" is a prefix of EVERY path...
});
app.get("/test", (req, res) => {
res.send("This never runs"); // ...so GET /test is answered above
});app.use("/", (req, res) => {
res.send("Catch-all!"); // "/" is a prefix of EVERY path...
});
app.get("/test", (req, res) => {
res.send("This never runs"); // ...so GET /test is answered above
});A request to /test gets "Catch-all!": app.use("/") matches every path, and it comes first. Fix it by putting specific routes first and broad ones last, or by using app.get instead of app.use.
Express vocabulary: words you'll see in every chapter
These terms come up in every Express project, not only DevTinder. Learn them once here:
| Term | What it is | Example |
|---|---|---|
| app | The object express() returns. You attach everything to it, then start it with listen. | const app = express() |
| route | An HTTP method plus a path that your server answers. | GET /users |
| route handler | The function that runs when a route matches. It receives req and res. | (req, res) => res.send("hi") |
req (request) | Everything the client sent: req.method, req.path, req.params, req.query, req.body, req.headers. | req.params.id |
res (response) | Your tools for answering: res.send(), res.json(), res.status(). Answer once per request. | res.status(404).json({ error: "Not found" }) |
| middleware | A function that runs before the handler, for many routes: logging, body parsing, auth checks. | app.use(express.json()) |
next | The third argument of a middleware. Call next() to pass the request on to the next function. | (req, res, next) => next() |
| router | A mini-app holding one group of routes, plugged into the main app. | express.Router() |
| mount | Plugging a router or middleware in at a path. | app.use("/users", usersRouter) |
Every request travels through these pieces in order. Express walks down your middleware and routes, top to bottom, until one of them sends a response:
Here is the whole picture in one file. It has no database and no DevTinder code, so you can run it as is (after npm install express):
// try-express.js
const express = require("express");
const app = express();
// middleware: runs for every request, then passes it on
app.use(express.json());
app.use((req, res, next) => {
console.log(req.method, req.path);
next();
});
const users = [{ id: 1, name: "Asha" }];
// routes + handlers: read from req, answer with res
app.get("/users/:id", (req, res) => {
const user = users.find((u) => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: "User not found" });
res.json(user);
});
app.post("/users", (req, res) => {
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user);
});
app.listen(3000, () => console.log("Listening on 3000"));// try-express.js
const express = require("express");
const app = express();
// middleware: runs for every request, then passes it on
app.use(express.json());
app.use((req, res, next) => {
console.log(req.method, req.path);
next();
});
const users = [{ id: 1, name: "Asha" }];
// routes + handlers: read from req, answer with res
app.get("/users/:id", (req, res) => {
const user = users.find((u) => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: "User not found" });
res.json(user);
});
app.post("/users", (req, res) => {
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user);
});
app.listen(3000, () => console.log("Listening on 3000"));Run node try-express.js, then try it from a second terminal:
curl localhost:3000/users/1
curl localhost:3000/users/9
curl -X POST localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Ravi"}'curl localhost:3000/users/1
curl localhost:3000/users/9
curl -X POST localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Ravi"}'Output:
{"id":1,"name":"Asha"}
{"error":"User not found"}
{"id":2,"name":"Ravi"}{"id":1,"name":"Asha"}
{"error":"User not found"}
{"id":2,"name":"Ravi"}The server terminal prints GET /users/1, GET /users/9 and POST /users, one line per request, from the logging middleware. The next chapters zoom into each piece: routes and req in Chapter S2 04: Routing and Request handlers, and middleware and next in Chapter S2 05: Middlewares and Error Handlers.
Step 5: Restart automatically while you code
Node.js loads your code once at startup. After every change you'd have to stop the server (Ctrl + C) and start it again. Two ways to automate that:
Option 1: Node's built-in watch mode (Node 18.11+, nothing to install):
node --watch src/app.jsnode --watch src/app.jsOption 2: nodemon, the long-time favourite, with more options:
npm install --save-dev nodemonnpm install --save-dev nodemonThen add scripts to package.json:
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
}"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
}Now npm run dev starts the server and restarts it every time you save. Use npm start in production, where you don't want automatic restarts on file changes.
Global vs local installs, and npx
The lectures install nodemon globally:
npm install -g nodemon # -g = global: available as a command everywherenpm install -g nodemon # -g = global: available as a command everywhere| Local install (default) | Global install (-g) | |
|---|---|---|
| Where | the project's node_modules/ | a system-wide folder |
Recorded in package.json? | yes | no |
Teammates and servers get it with npm install? | yes | no, everyone installs it separately, maybe a different version |
| Typical use | almost everything | general command-line tools you use across all projects |
For project tools, a local dev dependency is the safer choice: everyone gets the same version. npm scripts automatically find locally installed tools. To run one directly from the terminal, use npx:
npx nodemon src/app.js # runs the project's own nodemonnpx nodemon src/app.js # runs the project's own nodemonCommon mistakes
- Committing
node_modules/or.envto Git. Add both to.gitignorefirst thing. - Not committing
package-lock.json: teammates get different versions. app.use("/", ...)at the top, catching every request.- Forgetting to restart the server after a change (or forgetting to use nodemon/
--watch). EADDRINUSE: address already in use :::3000: your server is already running in another terminal. Stop it first.
Key takeaways
npm initcreatespackage.json: scripts, dependencies (needed to run) and devDependencies (needed to develop).- Versions use semver (
MAJOR.MINOR.PATCH);^allows minor updates,~only patches. node_modules/is never committed;package-lock.jsonalways is. Usenpm cion servers.- Express is a minimal framework on top of the
httpmodule.npm install expressgives you Express 5. app.use(path)matches all methods and all sub-paths;app.get(path)matches GET on the exact path. Routes are checked in order.- Use
node --watchor nodemon (as a dev dependency) to restart on changes.
Interview questions
Q1. What is package.json?
It's the manifest of a Node.js project: its name and version, the scripts you can run (npm start, npm run dev), and the packages it depends on, split into dependencies (needed in production) and devDependencies (needed only for development). npm install reads it to install everything.
Q2. What is the difference between package.json and package-lock.json?
package.json lists dependencies with version ranges (^5.1.0). package-lock.json records the exact installed version of every package in the dependency tree, so every install produces the same node_modules. Both should be committed.
Q3. What is the difference between dependencies and devDependencies?
dependencies are needed for the app to run (express, mongoose). devDependencies are only needed while developing or building (nodemon, jest, eslint). Production installs can skip dev dependencies with npm ci --omit=dev, making deployments smaller.
Q4. What do ^ and ~ mean in version numbers?
With semantic versioning (MAJOR.MINOR.PATCH), ^1.2.3 accepts any 1.x.x at or above 1.2.3 (minor and patch updates), while ~1.2.3 accepts only 1.2.x (patch updates). Neither allows a new major version, which may contain breaking changes.
Q5. What is the difference between npm install and npm ci?
npm install installs dependencies based on package.json and may update package-lock.json. npm ci deletes node_modules and installs exactly what package-lock.json says, failing if the two files disagree. npm ci is faster and reproducible, which is why CI pipelines and servers use it.
Q6. What is Express.js and why use it instead of the http module?
Express is a minimal, unopinionated web framework built on Node's http module. It adds routing (methods, paths, parameters), a middleware system, request body parsing, and helpers like res.json() and res.status(). You write far less boilerplate than with raw http, while keeping full control.
Q7. What is the difference between app.use() and app.get()?
app.get(path, handler) handles only GET requests whose path matches exactly (plus parameters). app.use(path, fn) runs for every method and for every path that starts with path as a whole segment (/user matches /user/42, not /users). app.use is meant for middleware and mounting routers.
Q8. What is npx?
npx runs a package's command-line tool: from the local node_modules/.bin if the package is installed in the project, or by downloading it temporarily if it isn't (for example npx create-vite@latest). It avoids global installs.
What's next
Your server has two routes. In Chapter S2 04: Routing and Request handlers you'll learn all the HTTP methods, route parameters and query strings, how Express matches paths, and how to test your API with Postman.