0
0
Expressframework~5 mins

Virtual path prefixes in Express

Choose your learning style9 modes available
Introduction

Virtual path prefixes let you group routes under a common starting path. This keeps your code organized and easy to manage.

You want to group all user-related routes under '/users' like '/users/login' and '/users/profile'.
You have an admin section and want all admin routes to start with '/admin'.
You want to mount a set of routes from another file or module under a specific path.
You want to serve static files from a specific URL path prefix.
Syntax
Express
app.use('/prefix', routerOrMiddleware);
The '/prefix' is the virtual path prefix where the router or middleware will be mounted.
All routes inside the router will be relative to this prefix.
Examples
This mounts the router at '/api'. So the route is accessible at '/api/hello'.
Express
const express = require('express');
const app = express();
const router = express.Router();

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

app.use('/api', router);
This serves static files from the 'public' folder under the '/static' URL path.
Express
app.use('/static', express.static('public'));
Sample Program

This example creates a router with a route '/info'. The router is mounted at '/docs'. So visiting '/docs/info' shows the router response. The home page is at '/'.

Express
const express = require('express');
const app = express();
const router = express.Router();

router.get('/info', (req, res) => {
  res.send('Info page inside router');
});

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

app.get('/', (req, res) => {
  res.send('Home page');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Virtual path prefixes do not change the actual route paths inside the router; they just add a prefix when mounted.

You can mount multiple routers with different prefixes to organize your app better.

Summary

Virtual path prefixes help organize routes under a common URL path.

Use app.use('/prefix', router) to mount routers or middleware.

This makes your app easier to maintain and scale.