WagnerMatosUK WagnerMatosUK - 2 months ago 16x
Node.js Question

How to separate the routes and models from app.js using NodeJS and Express

Ok, I'm creating an app using Node and Express, all is working, however I can see it'll soon become pretty difficult to manage all routes that are placed inside app.js. I did manage to get it working placing my models in its subdirectory (/models).

Here's my app current structure:

-- products
-- customers
-- ...

Inside app.js I've got:

var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
EmployeeProvider = require('./models/employeeprovider').EmployeeProvider,
Products = require('./models/products').Products,
Orders = require('./models/orders').Orders,
Customers = require('./models/customers').Customers,
checkAuth = function(req, res, next) {

if (!req.session.user_id) {

res.send('You are not authorized to view this page');

} else {




var app = express();

Then some configuration like port, views directory, rendering engine, etc.

Then also inside app.js I've got the routes:

app.get('/product/edit', auth, function(req, res) {

Products.findAll(function(error, prds){

res.render('product_edit', {

title: 'New Product',
products: prds




And because at the top I'm assigning the contents of models/products.js to a variable, all works fine. However keeping all routes inside app.js is not ideal. But if I move the routes to routes/product.js for instance and load the Products models like so:
var prod = require('../models/products.js')'
I get an error saying that object has no method findAll.

What am I doing wrong? How can I remove the routes from app.js?


As of express 4.x Router is added to support your case.

A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.

Example from expressjs site:

// routes/calendarRouter.js

var router = express.Router();

// invoked for any requested passed to this router
router.use(function(req, res, next) {
  // .. some logic here .. like any other middleware

// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
  // ..

Then in app.js:

var calendarRouter = require('./routes/calendarRouter');

// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', calendarRouter);