With signup, login and auth in place, app.js has grown into one long file. In this chapter you'll organize the backend the way real projects do, with Express routers, and build three more APIs: logout, view profile and edit profile (plus a bonus: changing the password).
In this chapter you'll learn
- what
express.Router()is, and how to split APIs into router files - how to mount routers in
app.js, and in what order Express tries them - a logout API, and what logging out with JWTs can and can't do
- profile view and profile edit APIs, with an allow-list of editable fields
- why the edit API uses
save()instead offindByIdAndUpdate
Before you start: read Chapter S2 10: Authentication, JWT & Cookies (userAuth, JWT cookies). The API list comes from Chapter S2 02: Features, HLD LLD and Planning.
The final API list
Grouped by feature, each group becomes one router:
| Router | Endpoints |
|---|---|
| authRouter | POST /signup, POST /login, POST /logout |
| profileRouter | GET /profile/view, PATCH /profile/edit, PATCH /profile/password |
| requestRouter | POST /request/send/:status/:toUserId, POST /request/review/:status/:requestId |
| userRouter | GET /user/requests/received, GET /user/connections, GET /user/feed |
The connection-request statuses, used everywhere from the URLs to the database, are spelled exactly:
interestedandignored: chosen by the sender (Chapter S2 12: Logical DB Query and Compound Indexes)acceptedandrejected: chosen by the receiver (Chapter S2 13: ref, Populate and Thought Process of writing API's)
Pick one spelling and use it everywhere: the schema's enum, the allowed-status arrays and the URLs. The original course notes mix ignore/ignored and interested/intrested. Mongoose compares enum values exactly, so a single typo means requests are rejected (`ignore` is not a valid enum value) or queries silently find nothing. This chapter and the next ones use ignored, interested, accepted and rejected.
Express Router
An express.Router() is a mini-application: it has its own routes and middleware, but can't run on its own. You build one per feature, then mount it onto the main app.
Think of a large office building: app.js is the reception desk, and each router is a department (Accounts, HR, Sales). Reception doesn't handle every request itself; it sends each visitor to the right department.
Folder structure
src/
├── app.js
├── config/database.js
├── middlewares/auth.js
├── models/user.js
├── routes/
│ ├── auth.js ← authRouter
│ ├── profile.js ← profileRouter
│ ├── request.js ← requestRouter
│ └── user.js ← userRouter
└── utils/validation.jssrc/
├── app.js
├── config/database.js
├── middlewares/auth.js
├── models/user.js
├── routes/
│ ├── auth.js ← authRouter
│ ├── profile.js ← profileRouter
│ ├── request.js ← requestRouter
│ └── user.js ← userRouter
└── utils/validation.jsA router file
// src/routes/auth.js
const express = require("express");
const bcrypt = require("bcryptjs");
const User = require("../models/user");
const { validateSignupData } = require("../utils/validation");
const authRouter = express.Router();
authRouter.post("/signup", async (req, res) => {
// ...the signup code from S2 09
});
authRouter.post("/login", async (req, res) => {
// ...the login code from S2 10
});
module.exports = authRouter;// src/routes/auth.js
const express = require("express");
const bcrypt = require("bcryptjs");
const User = require("../models/user");
const { validateSignupData } = require("../utils/validation");
const authRouter = express.Router();
authRouter.post("/signup", async (req, res) => {
// ...the signup code from S2 09
});
authRouter.post("/login", async (req, res) => {
// ...the login code from S2 10
});
module.exports = authRouter;The only change: app.post(...) becomes authRouter.post(...). A router has the same methods as the app: get, post, patch, delete, use.
Mounting the routers
// src/app.js
const express = require("express");
const cookieParser = require("cookie-parser");
const connectDB = require("./config/database");
const authRouter = require("./routes/auth");
const profileRouter = require("./routes/profile");
const requestRouter = require("./routes/request");
const userRouter = require("./routes/user");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use("/", authRouter);
app.use("/", profileRouter);
app.use("/", requestRouter);
app.use("/", userRouter);
connectDB().then(() => {
app.listen(process.env.PORT || 3000, () => console.log("Server listening on 3000"));
});// src/app.js
const express = require("express");
const cookieParser = require("cookie-parser");
const connectDB = require("./config/database");
const authRouter = require("./routes/auth");
const profileRouter = require("./routes/profile");
const requestRouter = require("./routes/request");
const userRouter = require("./routes/user");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use("/", authRouter);
app.use("/", profileRouter);
app.use("/", requestRouter);
app.use("/", userRouter);
connectDB().then(() => {
app.listen(process.env.PORT || 3000, () => console.log("Server listening on 3000"));
});- Global middleware (
express.json,cookieParser) is registered once, before the routers, so every router benefits. - Express tries the routers in order. A router without a matching route simply passes the request on to the next one. If none matches, Express answers 404.
- Mounting with a prefix is also common:
app.use("/profile", profileRouter)lets the router define/viewinstead of/profile/view. DevTinder mounts everything at/and writes full paths in the routers, which makes each route easy to find by searching.
Router-level middleware
A router can have its own middleware. For example, every profile route needs a logged-in user:
const profileRouter = express.Router();
profileRouter.use(userAuth); // runs for every route in THIS routerconst profileRouter = express.Router();
profileRouter.use(userAuth); // runs for every route in THIS routerDevTinder instead passes userAuth to each protected route, which makes it obvious, route by route, which ones are protected.
Logout API
// src/routes/auth.js
authRouter.post("/logout", (req, res) => {
res.clearCookie("token", { httpOnly: true, sameSite: "lax" });
res.send("Logout successful!");
});// src/routes/auth.js
authRouter.post("/logout", (req, res) => {
res.clearCookie("token", { httpOnly: true, sameSite: "lax" });
res.send("Logout successful!");
});res.clearCookie tells the browser to delete the cookie, by sending it back with an expiry date in the past. We checked the actual header Express 5 sends:
Set-Cookie: token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=LaxSet-Cookie: token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=LaxThe course does the same thing by hand:
res.cookie("token", null, { expires: new Date(Date.now()) });res.cookie("token", null, { expires: new Date(Date.now()) });Either works. Pass the same path/domain options you used when setting the cookie, or the browser treats it as a different cookie and keeps the old one.
Logging out deletes the cookie, but doesn't revoke the JWT. The token itself stays valid until its exp time (1 day here). If someone copied it before the user logged out, it still works for them. That's the trade-off of stateless JWTs (Chapter S2 10: Authentication, JWT & Cookies). Apps that need instant revocation keep short-lived access tokens plus refresh tokens in the database, or a deny-list of logged-out token IDs.
Profile view API
// src/routes/profile.js
const express = require("express");
const { userAuth } = require("../middlewares/auth");
const profileRouter = express.Router();
profileRouter.get("/profile/view", userAuth, async (req, res) => {
res.send(req.user); // userAuth already loaded the logged-in user
});// src/routes/profile.js
const express = require("express");
const { userAuth } = require("../middlewares/auth");
const profileRouter = express.Router();
profileRouter.get("/profile/view", userAuth, async (req, res) => {
res.send(req.user); // userAuth already loaded the logged-in user
});That's the whole route: userAuth did the hard work. One improvement: req.user is the full document, including the password hash. Don't send it to the client:
const { password, ...safeUser } = req.user.toObject();
res.send(safeUser);const { password, ...safeUser } = req.user.toObject();
res.send(safeUser);(Or exclude it everywhere with select: false on the schema's password field, and explicitly .select("+password") in login.)
Profile edit API
Validate which fields may change
// src/utils/validation.js
const validateEditProfileData = (req) => {
const allowedEditFields = [
"firstName",
"lastName",
"photoUrl",
"gender",
"age",
"about",
"skills",
];
return Object.keys(req.body).every((field) => allowedEditFields.includes(field));
};
module.exports = { validateSignupData, validateEditProfileData };// src/utils/validation.js
const validateEditProfileData = (req) => {
const allowedEditFields = [
"firstName",
"lastName",
"photoUrl",
"gender",
"age",
"about",
"skills",
];
return Object.keys(req.body).every((field) => allowedEditFields.includes(field));
};
module.exports = { validateSignupData, validateEditProfileData };emailId and password are deliberately not in the list: they need their own, more careful flows. _id can never be changed this way either.
The route
profileRouter.patch("/profile/edit", userAuth, async (req, res) => {
try {
if (!validateEditProfileData(req)) {
throw new Error("Invalid edit request");
}
const loggedInUser = req.user;
Object.keys(req.body).forEach((key) => (loggedInUser[key] = req.body[key]));
await loggedInUser.save();
res.json({
message: `${loggedInUser.firstName}, your profile was updated successfully`,
data: loggedInUser,
});
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});profileRouter.patch("/profile/edit", userAuth, async (req, res) => {
try {
if (!validateEditProfileData(req)) {
throw new Error("Invalid edit request");
}
const loggedInUser = req.user;
Object.keys(req.body).forEach((key) => (loggedInUser[key] = req.body[key]));
await loggedInUser.save();
res.json({
message: `${loggedInUser.firstName}, your profile was updated successfully`,
data: loggedInUser,
});
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});Why save() instead of findByIdAndUpdate?
Look at what happens: the route changes the fields on the loaded document and calls save().
save()runs every schema validator (minLength,min: 18,enum, customvalidate()) and sanitizer, exactly as on signup.findByIdAndUpdatewould skip them unless you rememberedrunValidators: true(Chapter S2 08: Data Sanitization & Schema Validations).res.json(...)sends an object as JSON (likeres.sendwith an object, but explicit about the intent).
Bonus: change password
profileRouter.patch("/profile/password", userAuth, async (req, res) => {
try {
const { currentPassword, newPassword } = req.body;
const isValid = await req.user.validatePassword(currentPassword); // schema method, S2 10
if (!isValid) throw new Error("Current password is incorrect");
if (!validator.isStrongPassword(newPassword)) {
throw new Error("New password is not strong enough");
}
req.user.password = await bcrypt.hash(newPassword, 10);
await req.user.save();
res.send("Password updated successfully");
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});profileRouter.patch("/profile/password", userAuth, async (req, res) => {
try {
const { currentPassword, newPassword } = req.body;
const isValid = await req.user.validatePassword(currentPassword); // schema method, S2 10
if (!isValid) throw new Error("Current password is incorrect");
if (!validator.isStrongPassword(newPassword)) {
throw new Error("New password is not strong enough");
}
req.user.password = await bcrypt.hash(newPassword, 10);
await req.user.save();
res.send("Password updated successfully");
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});Asking for the current password protects users who leave a device logged in: someone who sits down at their laptop can't lock them out.
Try it on its own
Routers are not specific to DevTinder. This file builds two routers, books and users, and mounts them on one app. In a real project each router goes in its own file under routes/, exactly like authRouter above:
npm install expressnpm install express// router-demo.js: two routers mounted on one app
const express = require("express");
const app = express();
// --- would be routes/books.js ---
const booksRouter = express.Router();
booksRouter.use((req, res, next) => {
console.log("booksRouter saw", req.method, req.originalUrl, "→ path inside router:", req.path);
next();
});
booksRouter.get("/", (req, res) => res.json(["Clean Code", "Node.js Design Patterns"]));
booksRouter.get("/:id", (req, res) => res.json({ book: req.params.id }));
// --- would be routes/users.js ---
const usersRouter = express.Router();
usersRouter.get("/", (req, res) => res.json(["Asha", "Ravi"]));
// --- app.js: mount each router at a prefix ---
app.use("/books", booksRouter);
app.use("/users", usersRouter);
app.listen(3000, () => console.log("Listening on 3000"));// router-demo.js: two routers mounted on one app
const express = require("express");
const app = express();
// --- would be routes/books.js ---
const booksRouter = express.Router();
booksRouter.use((req, res, next) => {
console.log("booksRouter saw", req.method, req.originalUrl, "→ path inside router:", req.path);
next();
});
booksRouter.get("/", (req, res) => res.json(["Clean Code", "Node.js Design Patterns"]));
booksRouter.get("/:id", (req, res) => res.json({ book: req.params.id }));
// --- would be routes/users.js ---
const usersRouter = express.Router();
usersRouter.get("/", (req, res) => res.json(["Asha", "Ravi"]));
// --- app.js: mount each router at a prefix ---
app.use("/books", booksRouter);
app.use("/users", usersRouter);
app.listen(3000, () => console.log("Listening on 3000"));Run node router-demo.js, then:
curl localhost:3000/books
curl localhost:3000/books/42
curl localhost:3000/users
curl localhost:3000/orderscurl localhost:3000/books
curl localhost:3000/books/42
curl localhost:3000/users
curl localhost:3000/ordersOutput:
["Clean Code","Node.js Design Patterns"]
{"book":"42"}
["Asha","Ravi"]
...Cannot GET /orders (Express's default 404 page)["Clean Code","Node.js Design Patterns"]
{"book":"42"}
["Asha","Ravi"]
...Cannot GET /orders (Express's default 404 page)and in the server terminal:
booksRouter saw GET /books → path inside router: /
booksRouter saw GET /books/42 → path inside router: /42booksRouter saw GET /books → path inside router: /
booksRouter saw GET /books/42 → path inside router: /42That log shows the key idea: mounting strips the prefix. The app sends everything starting with /books to booksRouter, and inside the router the path starts again from /. So the router file never repeats /books, and you could mount the same router at /v2/books without changing it. The router's own middleware (the logger) only runs for its requests, never for /users.
Common mistakes
- Forgetting
module.exports = router:requirethen returns an empty object, andapp.use("/", ...)throwsTypeError: argument handler must be a function(Express 5). - Registering
express.json()orcookieParser()after the routers:req.bodyandreq.cookiesare missing inside them. - Mismatched status spellings across schema, routes and queries.
- Sending
req.userwith the password hash to the client. - Editing profiles with
findByIdAndUpdatewithoutrunValidators. - Thinking logout makes the JWT invalid.
Key takeaways
express.Router()is a mini-app; build one per feature and mount it withapp.use().- Register global middleware (
express.json,cookieParser) before the routers. - Logout = clear the cookie (
res.clearCookie); the JWT stays valid until it expires. - Profile edit uses an allow-list and
save(), so all schema validators run. - Never send the password hash back; use one consistent spelling for statuses.
Interview questions
Q1. What is express.Router() and why use it?
It creates a modular, mountable set of routes and middleware, like a mini Express app without its own server. Routers let you split an API into feature files (auth, users, orders), keep app.js small, apply middleware to just one group of routes, and mount groups under a prefix (app.use("/api/users", usersRouter)).
Q2. How do you mount a router under a path prefix?
app.use("/api/users", usersRouter). Inside the router, paths are relative to the prefix: usersRouter.get("/:id", ...) handles GET /api/users/42. Inside those handlers, req.baseUrl is /api/users and req.originalUrl is the full path.
Q3. How do you log out a user with JWT authentication?
On the client side, delete the token: clear the cookie with res.clearCookie("token") (matching the original cookie options). That doesn't invalidate the token itself, which stays valid until it expires. For real revocation, use short-lived access tokens with server-stored refresh tokens that you delete on logout, or keep a deny-list of revoked token IDs (jti) until they expire.
Q4. Why might you prefer doc.save() over findByIdAndUpdate for an update?
save() runs the full document validation, sanitizers and save middleware (pre('save')), with this as the document. Query updates skip validators unless you pass runValidators: true, don't trigger save hooks, and update validators only see the changed fields. findByIdAndUpdate is faster (one round trip) and avoids overwriting concurrent changes to other fields, so it's still good for simple updates.
Q5. How do you keep the password hash out of API responses?
Several options: set select: false on the password field in the schema (then .select("+password") only where it's needed, like login); remove it before sending (const { password, ...rest } = user.toObject()); or define a toJSON transform on the schema that deletes it. The schema-level options are safest, because they apply everywhere.
Q6. How should a "change password" API work?
Require authentication and the current password, validate the strength of the new password, hash it with bcrypt and save it. Ideally, also invalidate other sessions or tokens (for example by storing a "password changed at" timestamp and rejecting tokens issued before it).
What's next
The profile APIs are done. In Chapter S2 12: Logical DB Query and Compound Indexes you'll build the heart of DevTinder: the ConnectionRequest model and the API to send a request, with careful validation, a pre("save") hook and indexes.