Namespaces help organize routes in Express by grouping related paths together. This keeps your code clean and easy to manage.
0
0
Namespaces for separation in Express
Introduction
You want to separate user-related routes from admin routes in your app.
You have multiple API versions and want to keep their routes distinct.
You want to group routes by feature, like products, orders, and customers.
You want to avoid route name conflicts by using prefixes.
You want to make your app easier to read and maintain.
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 a namespace app.use('/namespace', router);
The express.Router() creates a mini app for routes.
The app.use('/namespace', router) adds a prefix to all routes in the router.
Examples
This creates a
/user/profile route by adding the /user namespace.Express
const userRouter = express.Router(); userRouter.get('/profile', (req, res) => { res.send('User Profile'); }); app.use('/user', userRouter);
This creates a
/admin/dashboard route separate from other routes.Express
const adminRouter = express.Router(); adminRouter.get('/dashboard', (req, res) => { res.send('Admin Dashboard'); }); app.use('/admin', adminRouter);
Sample Program
This Express app uses two namespaces: /user and /admin. Each has its own router with routes inside. This keeps user and admin routes separate and organized.
Express
const express = require('express'); const app = express(); const userRouter = express.Router(); userRouter.get('/profile', (req, res) => { res.send('User Profile Page'); }); const adminRouter = express.Router(); adminRouter.get('/dashboard', (req, res) => { res.send('Admin Dashboard Page'); }); app.use('/user', userRouter); app.use('/admin', adminRouter); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Namespaces help avoid route conflicts by adding a clear prefix.
You can nest routers inside other routers for deeper organization.
Remember to use app.use() to connect routers with namespaces.
Summary
Namespaces group related routes under a common path prefix.
Use express.Router() to create route groups.
Attach routers to the main app with app.use('/namespace', router).