0
0
Expressframework~3 mins

Why Route prefixing in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change many routes' base path by editing just one line?

The Scenario

Imagine building a web app with many pages like /users, /users/profile, /users/settings, and you have to write each full path manually for every route.

The Problem

Manually typing full paths for every route is tiring, easy to make mistakes, and hard to update if the base path changes. It's like rewriting the same address over and over.

The Solution

Route prefixing lets you set a common starting path once, so all related routes automatically share it. This keeps your code clean and easy to maintain.

Before vs After
Before
app.get('/users/profile', handler);
app.get('/users/settings', handler);
After
const userRouter = express.Router();
userRouter.get('/profile', handler);
userRouter.get('/settings', handler);
app.use('/users', userRouter);
What It Enables

It enables organizing routes logically and updating base paths quickly without hunting through all your code.

Real Life Example

Think of a mailing address: instead of writing the city and street every time, you write it once and just add the house number for each letter.

Key Takeaways

Manually writing full route paths is repetitive and error-prone.

Route prefixing groups related routes under a shared base path.

This makes your code cleaner and easier to update.