Node.js Course
Node.js
/
Intermediate

Express Router

Definition

A mini Express application without a server. It acts as a complete middleware and routing system, allowing you to split massive applications into smaller, modular files.

Explain Like I'm New

If you put all 150 API routes in `server.js`, your file will be 5,000 lines long and impossible to read. The Router lets you create a completely separate `userRoutes.js` file just for Users, and a `productRoutes.js` file just for Products. You then 'plug' these files into the main server. It's the ultimate organization tool.

Real World Example

Building an API with versions. You can plug all your V1 routes into `/api/v1` (`app.use('/api/v1', v1Router)`), and completely separate V2 routes into `/api/v2`.

Common Use Cases

  • •Code organization
  • •Micro-architectures
  • •API Versioning

Terminal Output

bash / terminal
/* --- file: routes/userRoutes.js --- */ // const express = require('express'); // const router = express.Router(); // // This is relative to where the router is plugged in! // router.get('/', (req, res) => res.send('List of Users')); // router.get('/:id', (req, res) => res.send('Single User')); // module.exports = router; /* --- file: server.js --- */ // const express = require('express'); // const app = express(); // // 1. Import the modular router // const userRoutes = require('./routes/userRoutes'); // // 2. Mount the router onto a specific path // // Any traffic matching /api/users is funneled into the userRoutes file // app.use('/api/users', userRoutes); console.log("Express Router is the industry standard way to structure large Node applications.");

Interview Questions

basic

  • How do you create a Router instance?

intermediate

  • If a Router defines a `router.get('/profile')`, and you plug the router into `app.use('/users', router)`, what is the final URL?

Flash Cards

Question

How to create it?

Click to reveal answer
Answer

`const router = express.Router();`

Question

What is the final URL?

Click to reveal answer
Answer

The URLs combine! The final URL the client must hit is `/users/profile`. This makes nesting routes incredibly powerful.