Timo Timo - 1 year ago 112
CoffeeScript Question

Separating Routes and Middleware into Files (in Express.js)

I'd like to separate routes and middleware out of my main app.coffee-file. (I'm using Express.js.)

This file has grown extensively and is not easy to skim anymore.

How can I put those into separate files so they are still aware of each other?

Example of route that uses middleware:

app.post '/signup', signup.inputsOK, signup.userIsNew, signup.createUser, allowUser, (req, res) ->
res.redirect '/'

Every middleware function should be available for each route and each route should be available in the main app.coffee-file!

Thanks for ideas!

Answer Source

Remember that Express middlewares are just functions, so as long as the function is required it can be used.


hello_user = ( req, res, next ) ->
    res.json {"message": "hi"}

module.exports = {
    hello_user : hello_user


user_routes = require './user_routes' 
app.post '/signup', signup.inputsOK, signup.userIsNew, signup.createUser, allowUser, user_routes.hello_user

I would do the middleware setup like this: the app.coffee file is responsible for setting up the route with the middlewares and the actual business logic function... then all the last function needs to do is the actual work required. (This also makes the function easier to unit test, without having to fake out Express routing)

Alternatively with a little work you could separate out the routes and have each file do the app.add work. (I dislike this approach, but many apps do this).


setupUserRoutes = (app) ->
    app.post '/signup', signup.inputsOK, signup.userIsNew, signup.createUser, allowUser, (req, res) ->
      res.redirect '/'

module.exports = setupUserRoutes


app = express()

require( './user_routes' )(app)

Here you're passing the Express object around to each new module you import. Since you set you exports to be only the one function - which takes one parameter, the created Express object - you can create your routes with the required middleware

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download