Methods to extend an application

One thing you can do to extend an application if you are building a larger site is to build it using MVC (Model, View, Controller). We already have the view part sorted, so let's look at the other pieces. We have some sort of a controller setup with our routes directory. The next step will be to create a file for each. For example, we can have account.js, which will have the login, logout, and createAccount functions. We haven't really covered adding models to our app. We can create a directory called models, and then add a user model, for which we can find a user, update, and create a user to tie in with our account controller. Note that there are some other frameworks that build on Express in this way (sails.js is a good example). We are not using any so that you can see the insides, if you will, of the application.

Another key point from this chapter is to learn how to use middleware. In our app, we had 6 routes and 14 pieces (15, if you include the middleware that only runs on the /chat route) of middleware. There are three great reasons for this. Firstly, middleware allows you to create flexible and reusable code. We built a quick and dirty authentication module in just two pieces of middleware. If we decide to create a profile page, we just create a route like the following:

app.get('/profile', [util.requireAuthentication], routes.profile);

Then, when we build our profile template, we will know that the user object will be populated with the user's username. No more copying/pasting if statements in our routes check a session whether the user is logged in or not!

Next, there is a great ecosystem of current middleware. Everything we built in this app has a package that can do the same thing. As we covered, Express uses Connect internally, so we can use any of the Connect middleware. Currently, it has 18 bundled middleware (we have used quite a few already, such as csrf, sessions, body parsing, cookies, and static, to name a few). There are also many third-party middleware. We have used two: connect-redis and connect-flash. The Connect website has a list of the most popular third-party middleware on GitHub.

Finally, middleware functions are the perfect size for unit tests. We did not cover them here, but having a set of reusable and unit test-covered functions will make your life as a developer much better. We will cover unit testing with Nodeunit in Chapter 8, JavaScript Best Practices for Application Development.