Routes
Last Updated : Oct 2026
Routes are used to map URLs to specific controllers or actions in your Express application. They allow you to define how a specific URL should be handled and which controller or action should be executed when that URL is accessed.
Each route can have one or more handler functions, which are executed when the route is matched.
Syntax :
app.METHOD(PATH, HANDLER);
where:
- app is the Express application instance.
- METHOD is the HTTP method (GET, POST, PUT, DELETE, etc.).
- PATH is the URL path.
- HANDLER is the function that will be executed when the route is matched.
Note : Route paths can be strings or regular expressions.String paths match requests exactly. The dot (.) and hyphen (-) are interpreted literally.Query strings (the part after the ?) are not part of the route path.
Warring : The characters ?, +, *, [], (), and ! are reserved and cannot be used as literal characters in route paths, and braces are reserved for optional segments. Use \ to escape them if needed.
Creating a GET Route
//app.get("/{splat}", handler); If you also want / itself to match:
app.get("/", (req, res) => {
res.send("Hello, Express.js!");
});
app.get("/about", (req, res) => {
res.status(200).send("About Page"); // Status code and message(Recommended)
});
Creating a POST Route
app.post("/", (req, res) => {
res.send("Hello, Express.js! This is a POST request.");
});
Chaining Routes
app
.route("/book")
.get((req, res) => {
res.send("Get a random book");
})
.post((req, res) => {
res.send("Add a book");
})
.put((req, res) => {
res.send("Update the book");
});
Routes with Parameters
Parameters are placeholders in the route path that are replaced with actual values when the route is matched.The captured values are populated in the req.params object.They are three types :
Named Parameters
It capture single parameter values using a colon (:).
app.get("/user/:id", (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
app.get("/user/:id/:name", (req, res) => {
const userId = req.params.id;
const userName = req.params.name;
res.send(`User ID: ${userId}, Name: ${userName}`);
});
Use of - and . in parameter names
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
Wildcard Parameters
It captured as an array of path segments instead of a string using an asterisk (*).
app.get("/products/*paths", (req, res) => {
const params = req.params.paths;
res.send(`Wildcard parameters: ${params}`);
});
// Request URL: http://localhost:3000/products/abc/123
// Output: Wildcard parameters: [ 'abc', '123' ]
Optional Parameters
It uses braces ({}) to define optional segments.If segments are not provided, the parameter is omitted from req.params.
app.get("/:file{.:ext}", (req, res) => {
// GET /image.png => req.params = { file: 'image', ext: 'png' }
// GET /image => req.params = { file: 'image' }
res.send("ok");
});
app.get("/user/{:id}", (req, res) => {
// GET /user/42 => req.params = { id: '42' }
// GET /user/ => req.params = {}
// GET /user => 404, only the parameter is optional
res.send("ok");
});
app.get("/order{/:id}", (req, res) => {
// GET /order/42 => req.params = { id: '42' }
// GET /order => req.params = {}, the whole segment is optional
res.send("ok");
});
Structuring the server.js file
Instead of writing all the routes and logic in the server.js file, we can create a separate folder of routes and create a file for routes and import it in server.js or app.js or index.js file.
Let Suppose we have user multiple routes,
So we create a folder called routes, for logic part we create controllers folder and create a file called userRoutes.js,userController.js respectively and import it in server.js file.
Step 1: Create a folder called routes and controllers
mkdir routes controllers
Step 2: Create a file called userRoutes.js in the routes folder
Step 3: Create a file called userController.js in the controllers folder
Step 4: Write the user routes in the userRoutes.js file
import express from "express";
import {
getAllUsers,
getUserById,
createUser,
} from "../controllers/userController.js";
const router = express.Router();
router.route("/").get(getAllUsers);
router.route("/").post(createUser);
router.route("/:id").get(getUserById);
export default router;
Step 5: Write the user controller in the userController.js file
export const getAllUsers = (req, res) => {
res.send("Get all users");
};
export const getUserById = (req, res) => {
res.send("Get user by id");
};
export const createUser = (req, res) => {
res.send("Create user");
};
Step 6: Import the userRoutes.js file in the server.js file
import express from "express";
import userRoutes from "./routes/userRoutes.js";
const app = express();
app.use("/users", userRoutes);
app.listen(3000, () => {
console.log("Server started on port 3000");
});
