0
0
ExpressHow-ToBeginner · 3 min read

How to Use Route Prefix in Express for Cleaner Routes

In Express, you use app.use('/prefix', router) to add a route prefix. This means all routes defined in the router will be accessed under the /prefix path, helping organize routes neatly.
📐

Syntax

The basic syntax to use a route prefix in Express is:

  • app.use('/prefix', router): Mounts the router on the /prefix path.
  • router: An Express Router instance containing route handlers.
  • All routes inside router will be accessed with the /prefix prepended.
javascript
const express = require('express');
const app = express();
const router = express.Router();

// Define routes on router
router.get('/example', (req, res) => {
  res.send('Hello from example route');
});

// Use router with prefix
app.use('/prefix', router);

app.listen(3000);
💻

Example

This example shows how to create a router with routes and mount it on a prefix /api. Accessing /api/users will trigger the router's /users route.

javascript
import express from 'express';

const app = express();
const apiRouter = express.Router();

// Define a route inside the router
apiRouter.get('/users', (req, res) => {
  res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});

// Mount router with prefix '/api'
app.use('/api', apiRouter);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // When visiting http://localhost:3000/api/users // Response: [{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
⚠️

Common Pitfalls

Common mistakes when using route prefixes include:

  • Defining routes on app instead of the router, which ignores the prefix.
  • Forgetting to use app.use('/prefix', router) and instead defining routes directly on app.
  • Using trailing slashes inconsistently, which can cause unexpected route matching.
javascript
const express = require('express');
const app = express();
const router = express.Router();

// Wrong: defining route on app instead of router
app.get('/prefix/example', (req, res) => {
  res.send('This route ignores router prefix');
});

// Right: define route on router
router.get('/example', (req, res) => {
  res.send('This route respects prefix');
});

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

app.listen(3000);
📊

Quick Reference

Tips for using route prefixes in Express:

  • Always create a Router instance for grouped routes.
  • Use app.use('/prefix', router) to apply the prefix.
  • Define routes relative to the router without repeating the prefix.
  • Keep prefixes consistent and avoid trailing slashes.

Key Takeaways

Use app.use('/prefix', router) to add a route prefix in Express.
Define routes on a Router instance to keep code organized and reusable.
Routes inside the router are accessed with the prefix automatically prepended.
Avoid defining prefixed routes directly on app to prevent confusion.
Keep route prefixes consistent and avoid trailing slashes for predictable routing.