0
0
Expressframework~5 mins

Route prefixing in Express

Choose your learning style9 modes available
Introduction
Route prefixing helps organize your web app by grouping similar routes under a shared starting path. It keeps your code tidy and easier to manage.
When you want to group all user-related routes under '/users' like '/users/login' and '/users/register'.
When building an API and you want all version 1 routes to start with '/api/v1'.
When you have admin routes and want them all to start with '/admin' for clarity and security.
When splitting routes into separate files but want them to share a common path prefix.
When you want to apply middleware only to a group of routes sharing the same prefix.
Syntax
Express
const express = require('express');
const app = express();
const router = express.Router();

// Define routes on router
router.get('/path', (req, res) => {
  res.send('response');
});

// Use router with prefix
app.use('/prefix', router);
You create a router to hold routes, then attach it to the main app with a prefix.
All routes inside the router will automatically start with the prefix you set.
Examples
All routes in userRouter start with '/users'. So '/users/login' shows 'User login page'.
Express
const express = require('express');
const app = express();
const userRouter = express.Router();

userRouter.get('/login', (req, res) => {
  res.send('User login page');
});

app.use('/users', userRouter);
This prefixes all apiRouter routes with '/api/v1'. So '/api/v1/data' returns JSON data.
Express
const express = require('express');
const app = express();
const apiRouter = express.Router();

apiRouter.get('/data', (req, res) => {
  res.json({ message: 'API data' });
});

app.use('/api/v1', apiRouter);
Sample Program
This program creates a router with one route '/hello'. The router is used with prefix '/greet'. So visiting '/greet/hello' shows 'Hello from router!'.
Express
const express = require('express');
const app = express();
const router = express.Router();

router.get('/hello', (req, res) => {
  res.send('Hello from router!');
});

app.use('/greet', router);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes
Route prefixing helps keep your app organized and makes it easier to add or change groups of routes.
You can use multiple routers with different prefixes in the same app.
Middleware can be applied to routers to affect all prefixed routes at once.
Summary
Route prefixing groups routes under a shared path to organize your app.
Create a router, define routes on it, then attach it to the app with a prefix.
This makes your URLs cleaner and your code easier to maintain.