0
0
Expressframework~5 mins

Separating routes into files in Express

Choose your learning style9 modes available
Introduction

Separating routes into files helps keep your code organized and easier to manage. It makes your app cleaner and simpler to understand.

When your app has many routes and the main file becomes too long.
When you want to group related routes together, like user routes in one file and product routes in another.
When working in a team, so different people can work on different route files without conflicts.
When you want to reuse routes in different parts of your app or in other apps.
Syntax
Express
const express = require('express');
const router = express.Router();

// Define routes
router.get('/path', (req, res) => {
  res.send('response');
});

module.exports = router;

Use express.Router() to create a new router object.

Export the router to use it in your main app file.

Examples
This example creates a route that sends a greeting message.
Express
const express = require('express');
const router = express.Router();

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

module.exports = router;
This example shows a POST route for form submission.
Express
const express = require('express');
const router = express.Router();

router.post('/submit', (req, res) => {
  res.send('Form submitted');
});

module.exports = router;
Sample Program

This example shows how to separate user-related routes into a users.js file inside a routes folder. The main app file imports and uses these routes under the /users path.

Express
// routes/users.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('User list');
});

router.get('/:id', (req, res) => {
  res.send(`User details for ID: ${req.params.id}`);
});

module.exports = router;

// app.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');

app.use('/users', userRoutes);

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

Always use app.use() to connect your route files to the main app.

Keep route files focused on related routes to stay organized.

Remember to export your router with module.exports.

Summary

Separating routes into files keeps your app clean and organized.

Use express.Router() to create route modules.

Import and use route files in your main app with app.use().