As an Express.js application grows, you may have many API endpoints.
For example:
app.get("/users", ...);
app.post("/users", ...);
app.put("/users/:id", ...);
app.delete("/users/:id", ...);
app.get("/products", ...);
app.post("/products", ...);
This is fine for a small application, but keeping all routes in server.js or app.js can quickly become difficult to maintain.
Express.js provides express.Router() to help organize routes into separate files.
In this article, we'll learn:
- What routing means in Express.js
- What
express.Router()is - How to create a router
- Different HTTP methods
router.route()- Route parameters
- Router-level middleware
- How to organize routes and controllers
- A practical project structure
What Is Routing in Express.js?
Routing determines how your application responds to a specific HTTP method and URL.
For example:
app.get("/users", (req, res) => {
res.json({
message: "Get users"
});
});
Here:
GET → HTTP method
/users → route
callback → route handler
When the client sends:
GET /users
Express executes the callback function.
Why Do We Need a Router?
Imagine your application has APIs for:
- Users
- Products
- Orders
- Authentication
- Payments
If everything is inside server.js, the file can become very large.
Instead, we can organize routes like this:
src/
├── routes/
│ ├── user.routes.js
│ ├── product.routes.js
│ ├── order.routes.js
│ └── auth.routes.js
│
└── server.js
Each router handles a particular part of the application.
That's where express.Router() comes in.
What Is express.Router()?
express.Router() creates a new router object.
const express = require("express");
const router = express.Router();
You can define routes using this router:
router.get("/users", (req, res) => {
res.json({
message: "Get users"
});
});
Then export it:
module.exports = router;
The router can then be imported into your main Express application.
Creating Your First Router
Let's create a user router.
routes/user.routes.js
const express = require("express");
const router = express.Router();
router.get("/users", (req, res) => {
res.json({
message: "Get users"
});
});
module.exports = router;
Now import the router into server.js.
server.js
const express = require("express");
const userRoutes = require("./routes/user.routes");
const app = express();
app.use("/api", userRoutes);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Now the API endpoint becomes:
GET /api/users
Why?
Because:
app.use("/api", userRoutes);
adds /api as the base path.
And the router contains:
router.get("/users", ...);
So:
/api + /users
↓
/api/users
Different HTTP Methods in Express Router
The most commonly used HTTP methods are:
router.get()
router.post()
router.put()
router.patch()
router.delete()
Each method represents a different type of operation.
1. router.get()
GET is generally used to retrieve data.
router.get("/users", (req, res) => {
res.json({
message: "Get all users"
});
});
Request:
GET /api/users
To get a specific user:
router.get("/users/:id", (req, res) => {
res.json({
id: req.params.id
});
});
Request:
GET /api/users/101
2. router.post()
POST is generally used to create a new resource.
router.post("/users", (req, res) => {
res.status(201).json({
message: "User created"
});
});
Request:
POST /api/users
The request body might be:
{
"name": "John",
"email": "john@example.com"
}
3. router.put()
PUT is generally used to completely replace or update an existing resource.
router.put("/users/:id", (req, res) => {
res.json({
message: "User updated",
id: req.params.id
});
});
Request:
PUT /api/users/101
Example body:
{
"name": "John",
"email": "john@example.com",
"age": 30
}
The typical idea behind PUT is that the client sends the complete representation of the resource it wants to replace.
4. router.patch()
PATCH is generally used for a partial update.
router.patch("/users/:id", (req, res) => {
res.json({
message: "User partially updated",
id: req.params.id
});
});
Request:
PATCH /api/users/101
You might send only the field that needs to change:
{
"name": "John Smith"
}
A simple way to remember:
PUT
→ Replace/update the resource
PATCH
→ Update specific fields
The exact update semantics ultimately depend on how your API implements them.
5. router.delete()
DELETE is generally used to delete a resource.
router.delete("/users/:id", (req, res) => {
res.json({
message: "User deleted",
id: req.params.id
});
});
Request:
DELETE /api/users/101
What Is router.route()?
router.route() allows you to define multiple HTTP methods for the same URL path in one place.
Without router.route():
router.get("/users", getUsers);
router.post("/users", createUser);
With router.route():
router
.route("/users")
.get(getUsers)
.post(createUser);
Both approaches create the same two routes.
The main benefit is that related methods are grouped together.
Why Is router.route() Useful?
Consider this API:
GET /api/users/:id
PUT /api/users/:id
PATCH /api/users/:id
DELETE /api/users/:id
Without router.route():
router.get("/users/:id", getUser);
router.put("/users/:id", updateUser);
router.patch("/users/:id", updateUser);
router.delete("/users/:id", deleteUser);
Notice that we repeat:
/users/:id
multiple times.
Using router.route():
router
.route("/users/:id")
.get(getUser)
.put(updateUser)
.patch(updateUser)
.delete(deleteUser);
This is easier to read because all operations for /users/:id are grouped together.
Complete router.route() Example
const express = require("express");
const router = express.Router();
// /api/users
router
.route("/users")
.get(getUsers)
.post(createUser);
// /api/users/:id
router
.route("/users/:id")
.get(getUser)
.put(updateUser)
.patch(updateUser)
.delete(deleteUser);
module.exports = router;
This creates:
GET /api/users
POST /api/users
GET /api/users/:id
PUT /api/users/:id
PATCH /api/users/:id
DELETE /api/users/:id
router.route() vs Individual Methods
Both approaches are valid.
Individual methods
router.get("/users", getUsers);
router.post("/users", createUser);
Using router.route()
router
.route("/users")
.get(getUsers)
.post(createUser);
router.route() is particularly useful when several HTTP methods operate on the same path.
router.route() With Middleware
You can also use middleware with router.route().
For example:
router
.route("/users/:id")
.get(authMiddleware, getUser)
.put(authMiddleware, updateUser)
.delete(authMiddleware, deleteUser);
If the same middleware should run for every method, you can use .all():
router
.route("/users/:id")
.all(authMiddleware)
.get(getUser)
.put(updateUser)
.patch(updateUser)
.delete(deleteUser);
Here:
.all(authMiddleware)
runs the middleware for all HTTP methods defined on that route.
Route Parameters With express.Router()
Route parameters are commonly used when working with individual resources.
For example:
router.get("/users/:id", (req, res) => {
console.log(req.params.id);
res.json({
id: req.params.id
});
});
Request:
GET /api/users/101
Then:
req.params.id
contains:
101
You can also have multiple parameters:
router.get(
"/users/:userId/orders/:orderId",
(req, res) => {
res.json({
userId: req.params.userId,
orderId: req.params.orderId
});
}
);
Request:
GET /api/users/101/orders/500
Router-Level Middleware
One useful feature of express.Router() is that middleware can be applied to a group of routes.
For example:
const authMiddleware = (req, res, next) => {
console.log("Authentication check");
next();
};
You can apply it to the router:
router.use(authMiddleware);
Now the middleware applies to routes handled by that router.
You can also apply middleware only to a particular route:
router.get(
"/profile",
authMiddleware,
(req, res) => {
res.json({
message: "Profile"
});
}
);
This is useful for:
- Authentication
- Authorization
- Validation
- Logging
- Request processing
A Better Way to Organize Routes
For a growing application, avoid putting all logic inside the route file.
Instead of:
router.get("/users", (req, res) => {
// lots of business logic
});
use a controller.
user.controller.js
const getUsers = (req, res) => {
res.json({
message: "Get users"
});
};
const createUser = (req, res) => {
res.status(201).json({
message: "Create user"
});
};
module.exports = {
getUsers,
createUser
};
Then your router becomes:
user.routes.js
const express = require("express");
const {
getUsers,
createUser
} = require("../controllers/user.controller");
const router = express.Router();
router
.route("/")
.get(getUsers)
.post(createUser);
module.exports = router;
And in server.js:
app.use("/api/users", userRoutes);
Now:
GET /api/users
POST /api/users
are handled by the user router.
Complete User Router
A practical router could look like this:
const express = require("express");
const {
getUsers,
createUser,
getUser,
updateUser,
deleteUser
} = require("../controllers/user.controller");
const router = express.Router();
router
.route("/")
.get(getUsers)
.post(createUser);
router
.route("/:id")
.get(getUser)
.put(updateUser)
.patch(updateUser)
.delete(deleteUser);
module.exports = router;
Then:
app.use("/api/users", userRoutes);
The final API becomes:
GET /api/users
POST /api/users
GET /api/users/:id
PUT /api/users/:id
PATCH /api/users/:id
DELETE /api/users/:id
This is a clean and common way to structure REST APIs.
Recommended Project Structure
As your Express.js application grows, you can organize it like this:
src/
│
├── controllers/
│ └── user.controller.js
│
├── routes/
│ └── user.routes.js
│
├── middleware/
│ └── auth.middleware.js
│
├── services/
│ └── user.service.js
│
├── models/
│ └── user.model.js
│
└── server.js
The basic request flow becomes:
Client
↓
Router
↓
Middleware
↓
Controller
↓
Service
↓
Database
↓
Response
This separation makes the application easier to understand and maintain.
app.get() vs router.get()
You may wonder about the difference between:
app.get("/users", handler);
and:
router.get("/users", handler);
app.get() registers a route directly on the Express application:
app.get("/users", handler);
router.get() registers a route on a router:
const router = express.Router();
router.get("/users", handler);
That router can then be mounted:
app.use("/api", router);
This makes express.Router() useful for creating modular route files.
app.route() vs router.route()
Express also provides app.route().
For example:
app
.route("/users")
.get(getUsers)
.post(createUser);
This is similar to:
router
.route("/users")
.get(getUsers)
.post(createUser);
The difference is where the route is registered.
app.route()
Registers routes directly on the Express application.
router.route()
Registers routes on an express.Router() instance.
In larger applications, router.route() is usually more useful because it allows you to keep routes in separate modules.
Common Mistakes
1. Putting everything in server.js
This may work initially, but the file can become difficult to maintain.
Instead, separate routes into modules.
2. Mixing business logic with routes
Avoid putting database operations and complex business logic directly inside route definitions.
Prefer:
Route
↓
Controller
↓
Service
3. Forgetting to export the router
Remember:
module.exports = router;
Otherwise you won't be able to import it into your main application.
4. Forgetting to mount the router
Creating a router isn't enough.
You also need:
app.use("/api/users", userRoutes);
Final Thoughts
express.Router() is an important part of building organized Express.js applications.
Instead of keeping every endpoint in one file, you can create separate routers for different resources:
users
products
orders
authentication
payments
The commonly used router methods are:
router.get()
router.post()
router.put()
router.patch()
router.delete()
And when multiple methods use the same URL, router.route() makes the code cleaner:
router
.route("/:id")
.get(getUser)
.put(updateUser)
.patch(updateUser)
.delete(deleteUser);
The key idea is:
express.Router()helps organize routes, whilerouter.route()helps group multiple HTTP methods for the same path.
For a small application, you can keep routing simple. As the application grows, separating routes, middleware, controllers, services, and models will make your Express.js API much easier to maintain.