34

I'm creating an app using Node and Express. However, I can see it'll soon become difficult to manage all the routes that are placed inside app.js. I have placed all my models in a subdirectory /models.

Here's my app current structure:

app.js
models
  -- products
  -- customers
  -- ...
public
views
node_modules

In app.js:

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 {
        next();
      }
    };

var app = express();

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

Further down 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
    });
  });
});

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 and load the Products models:

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?

1

3 Answers 3

34

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 express  = require('express');
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
  next();
});

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

module.exports = router;

Then in app.js:

// skipping part that sets up app

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

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

// rest of logic
4
  • Shouldn't it be app.use('/calendar', require('./routes/x'));? Commented Jul 31, 2015 at 3:55
  • Sure @Brennen, modified to make it clearer. Before I skipped the part where router was required.
    – Ivar
    Commented Aug 4, 2015 at 5:42
  • 1
    looks like the calendarRouter.js file is missing some export ?
    – jujule
    Commented Aug 5, 2016 at 15:07
  • why module.exports=router is missing from calenderRouter.js file ? Commented Oct 12, 2016 at 9:02
33

Since I don't like repetition, here's what I do:

// app.js
//...
var routes = requireDir('./routes'); // https://www.npmjs.org/package/require-dir
for (var i in routes) app.use('/', routes[i]);
//...

And each file in routes is like:

// routes/someroute.js
var express  = require('express');
var router   = express.Router();

router.get('/someroute', function(req, res) {
    res.render('someview', {});
});

module.exports = router;

This way you can avoid long repetitive lists like this one:

app.use('/'           , require('./routes/index'));
app.use('/repetition' , require('./routes/repetition'));
app.use('/is'         , require('./routes/is'));
app.use('/so'         , require('./routes/so'));
app.use('/damn'       , require('./routes/damn'));
app.use('/boring'     , require('./routes/boring'));

Edit: these long examples assume each route file contains something like the following:

var router = express.Router();
router.get('/', function(req, res, next) {
    // ...
    next();
});
module.exports = router;

All of them could be mounted to "root", but what for them is "root", is actually a specific path given to app.use, because you can mount routes into specific paths (this also supports things like specifying the path with a regex, Express is quite neat in regards to what you can do with routing).

5
  • 2
    This seems like quite a nice idea but as I'm new to Node.js and Express I have a question. I see that you're saving the hassle of writing each individual route (/repetition, /is, etc.) but won't app.use('/', routes[i]); only set the required route on the '/' route? The long example you gave in the end is different, i.e. it's app.use('/route', require('./routes/route'));. I hope that makes sense. Commented Oct 5, 2014 at 11:14
  • 1
    @DarrylYoung Tried to clear it up, see if it makes more sense now :) Commented Oct 6, 2014 at 17:31
  • great answer! tried to figure out what i did wrong with module.exports.router and you put me in good track with module.exports = router; Commented Apr 18, 2015 at 8:09
  • Sorry, i didn't get why this works (but i get how @Ivar Calendar answer). What if the URL is /calendar and in the Calendar route i have only set router.get('/', ...)? Can you elaborate on how app.use('/', ...) works? Thanks!
    – Fernando
    Commented Sep 8, 2015 at 8:47
  • @Fernando each route is defined and exported in a file in the routes folder. each file there is required and app.used directly. See it like this: when you call app.use('/', someRoute) the root of someRoute is merged on the root of the app, so if the route was defined as mounted at '/calendar', you'll now have a route like that in your app. You can create fresh routes with express.Router() and mount them later (not only on '/' but any path) with app.use() Commented Oct 8, 2015 at 5:18
21

I can suggest you this file structure (according to Modular web applications with Node.js and Express from tjholowaychuk):

app.js
   modules
      users
         index.js
         model.js
      users-api
         index.js
      static-pages
         index.js

user-api and static-pages export expressjs applications, you can easily mount them in app.js. In users module you can describe some Data Access operations and all methods about manipulating with the User entity (like create, update etc.). Our API module will use all these methods.

And here is sample code of app.js file (without common express stuff, only mounting routes from different modules):

var express = require('express');
var app = express();

// mount all the applications
app.use('/api/v1', require("user-api"));
app.use(require("static-pages"));

app.listen(3000);

To use your modules this way you must start your app like this NODE_PATH=modules node app.js (i put this line to package.json file in scripts section).

Here is sample code of users module:

index.js

User = require("./model");

module.exports = {
    get: function(id, callback) {
        User.findOne(id, function(err, user) {
           callback(err, user);
        });
    },
    create: function(data, callback) {
        // do whatever with incoming data here
        data = modifyDataInSomeWay(data);
        var newUser = new User(data);
        newUser.save(function(err, savedUser) {
            // some logic here
            callback(err, savedUser); 
        });
    }
};

model.js (with Mongoose stuff for example of course!)

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var User = new Schema({
    firstname   : {type: String, required: false},
    lastname    : {type: String, required: false},
    email       : {type: String, required: true}
});

module.exports = mongoose.model('user', User);

And example of user-api module (here is the main part of the answer about separating routes and models).

var users = require("users");

var express = require("express");
var app = module.exports = express(); // we export new express app here!

app.post('/users', function(req, res, next) {
    // try to use high-level calls here
    // if you want something complex just create another special module for this
    users.create(req.body, function(err, user) {
        if(err) return next(err); // do something on error
        res.json(user); // return user json if ok
    });
});

And example of static-pages. If you are not going to build a kind of REST interface you may simply create several modules that will render pages only.

var express = require("express");
var app = module.exports = express(); // we export new express app here again!

app.get('/', function(req, res, next) {
    res.render('index', {user: req.user});
});

app.get('/about', function(req, res, next) {
    // get data somewhere and put it in the template
    res.render('about', {data: data});
});

Of course you can do whatever you want with modules. The main idea about expressjs is to use a lot of small apps instead of single one.

About nodejs modules you can read stackoverflow and docs.

Hope this helps.

4
  • I don't see the logic of separating users and users-api... the api stuff should be in the users dir, otherwise that will get convoluted quick
    – AlxVallejo
    Commented Oct 20, 2015 at 1:15
  • @AlxVallejo thanks for comment! You are absolutely right in context of this question but not in context of application where i used separate folders for models and APIs (it is more complex then this super simple example). Commented Oct 28, 2015 at 14:00
  • from where this "users" came from ? var users = require("users"); is from ?
    – duardbr
    Commented Nov 18, 2016 at 9:04
  • @duardbr users is a module for working with Users entities (you can find an example in my post). It can be as simple as get/create/update/remove or contain any complex logic and methods. Commented Dec 4, 2016 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.