0
0
Expressframework~30 mins

Namespaces for separation in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Namespaces for Separation in Express
📖 Scenario: You are building a simple web server using Express.js. You want to organize your routes into separate namespaces to keep your code clean and easy to manage.
🎯 Goal: Create an Express server with two separate namespaces: /api/users and /api/products. Each namespace should respond with a simple JSON message.
📋 What You'll Learn
Create an Express app instance
Create two routers: usersRouter and productsRouter
Mount usersRouter on /api/users
Mount productsRouter on /api/products
Each router should have a GET route on / that sends a JSON response
💡 Why This Matters
🌍 Real World
Organizing routes into namespaces helps keep large Express applications clean and maintainable by grouping related routes together.
💼 Career
Understanding how to use routers and namespaces in Express is essential for backend developers building scalable web APIs.
Progress0 / 4 steps
1
Create the Express app and users router
Create an Express app by calling express() and assign it to app. Then create a router by calling express.Router() and assign it to usersRouter.
Express
Need a hint?

Use const app = express() to create the app and const usersRouter = express.Router() to create the router.

2
Create the products router
Create another router by calling express.Router() and assign it to productsRouter.
Express
Need a hint?

Create productsRouter the same way as usersRouter.

3
Add GET routes to both routers
Add a GET route on / to usersRouter that sends JSON { message: 'Users namespace' }. Also add a GET route on / to productsRouter that sends JSON { message: 'Products namespace' }.
Express
Need a hint?

Use router.get('/', (req, res) => { res.json(...) }) for each router.

4
Mount routers on namespaces and start server
Mount usersRouter on /api/users and productsRouter on /api/products using app.use(). Then start the server on port 3000 using app.listen().
Express
Need a hint?

Use app.use('/api/users', usersRouter) and app.use('/api/products', productsRouter). Then start the server with app.listen(3000).