Chapter 2. Designing a MEAN stack architecture

This chapter covers

  • Introducing a common MEAN stack architecture
  • Considerations for single-page applications
  • Discovering alternative MEAN stack architectures
  • Designing an architecture for a real application
  • Planning a build based on the architecture design

In chapter 1 we took a look at the component parts of the MEAN stack and how they fit together. In this chapter we’re going to look at how they fit together in more detail.

We’ll start off by looking at what some people think of as the MEAN stack architecture, especially when they first encounter the stack. Using some examples we’ll explore why you might use a different architecture, and switch things up a bit and move things around. MEAN is a very powerful stack and can be used to solve a diverse range of problems ... if you get creative with how you design your solutions.

2.1. A common MEAN stack architecture

A common way to architect a MEAN stack application is to have a representational state transfer (REST) API feeding a single-page application. The API is typically built with MongoDB, Express, and Node.js, with the SPA being built in AngularJS. This approach is particularly popular with those who come to the MEAN stack from an AngularJS background and are looking for a stack that gives a fast, responsive API. Figure 2.1 illustrates the basic setup and data flow.

Figure 2.1. A common approach to MEAN stack architecture, using MongoDB, Express, and Node.js to build a REST API that feeds JSON data to an AngularJS SPA run in the browser

What is a REST API?

REST stands for REpresentational State Transfer, which is an architectural style rather than a strict protocol. REST is stateless—it has no idea of any current user state or history.

API is an abbreviation for application program interface, which enables applications to talk to each other.

So a REST API is a stateless interface to your application. In the case of the MEAN stack the REST API is used to create a stateless interface to your database, enabling a way for other applications to work with the data.

Figure 2.1 is a great setup, ideal if you have, or intend to build, an SPA as your user-facing side. AngularJS is designed with a focus on building SPAs, pulling in data from a REST API, as well as pushing it back. MongoDB, Express, and Node.js are also extremely capable when it comes to building an API, using JSON all the way through the stack including the database itself.

This is where many people start with the MEAN stack, looking for an answer to the question, “I’ve built an application in AngularJS; now where do I get the data?”

Having an architecture like this is great if you have an SPA, but what if you don’t have or want to use an SPA? If this is the only way you think of the MEAN stack, you’re going to get a bit stuck and start looking elsewhere. But the MEAN stack is very flexible. All four components are very powerful and have a lot to offer.

2.2. Looking beyond SPAs

Coding an SPA in AngularJS is like driving a Porsche along a coastal road with the roof down. Both are amazing. They’re fun, fast, sexy, agile, and very, very capable. And it’s most likely that both are a vast improvement on what you’ve been doing before.

But sometimes they’re not appropriate. If you want to pack up the surfboards and take your family away for the week you’re going to struggle with the sports car. As amazing as your car may be, in this case you’re going to want to use something different. It’s the same story with SPAs. Yes, building them in AngularJS is amazing, but sometimes it’s not the best solution to your problem.

Let’s take a brief look at some things to bear in mind about SPAs when designing a solution and deciding whether a full SPA is right for your project or not. This section isn’t intended to be in any way “anti-SPA.” SPAs generally offer a fantastic user experience while reducing the load on your servers, and therefore also your hosting costs. In sections 2.3.1 and 2.3.2 we’ll look at a good use case for an SPA and a bad one, and we’ll actually build one by the end of this book!

2.2.1. Hard to crawl

JavaScript applications are very hard for search engines to crawl and index. Most search engines look at the HTML content on a page but don’t download or execute much JavaScript. For those that do, the actual crawling of JavaScript-created content is nowhere near as good as content delivered by the server. If all of your content is served via a JavaScript application then you cannot be sure how much of it will be indexed.

A related downside is that automatic previews from social-sharing sites like Facebook, LinkedIn, and Pinterest don’t work very well. This is also because they look at the HTML of the page you’re linking to and try to extract some relevant text and images. Like search engines they don’t run JavaScript on the page, so content served by JavaScript won’t be seen.

Making an SPA crawlable

There are a couple of workarounds to make it look as though your site is crawlable. Both involve creating separate HTML pages that mirror the content of your SPA. You can have your server create an HTML-based version of your site and deliver that to crawlers, or you can use a headless browser such as PhantomJS to run your JavaScript application and output the resulting HTML.

Both of these require quite a bit of effort, and can end up being a maintenance headache if you have a large, complex site. There are also potential search engine optimization (SEO) pitfalls. If your server-generated HTML is deemed to be too different from the SPA content then your site will be penalized. Running PhantomJS to output the HTML can slow down the response speed of your pages, which is something for which search engines—Google in particular—downgrade you.

Does it matter?

Whether this matters or not depends on what you want to build. If the main growth plan for whatever you’re building is through search engine traffic or social sharing then this is something you want to give a great deal of thought to. If you’re creating something small that will stay small then managing the workarounds is achievable, whereas at a larger scale you’ll struggle.

On the other hand, if you’re building an application that doesn’t need much SEO—or indeed if you want your site to be harder to scrape—then this isn’t an issue you need to be concerned about. It could even be an advantage.

2.2.2. Analytics and browser history

Analytics tools like Google Analytics rely heavily on entire new pages loading in the browser, initiated by a URL change. SPAs don’t work this way. There’s a reason they’re called single-page applications!

After the first page load, all subsequent page and content changes are handled internally by the application. So the browser never triggers a new page load, nothing gets added to the browser history, and your analytics package has no idea who’s doing what on your site.

Adding page loads to an SPA

You can add page load events to an SPA using the HTML5 history API; this will help you integrate analytics. The difficulty comes in managing this and ensuring that everything is being tracked accurately, which involves checking for missing reports and double entries.

The good news is that you don’t have to build everything from the ground up. There are several open source analytics integrations for AngularJS available online, addressing most of the major analytics providers. You still have to integrate them into your application and make sure that everything is working correctly, but you don’t have to do everything from scratch.

Is it a major problem?

The extent to which this is a problem depends on your need for undeniably accurate analytics. If you want to monitor trends in visitor flows and actions then you’re probably going to find it easy to integrate. The more detail and definite accuracy you need, the more work it is to develop and test. While it’s arguably much easier to just include your analytics code on every page of a server-generated site, analytics integration isn’t likely to be the sole reason that you choose a non-SPA route.

2.2.3. Speed of initial load

SPAs have a slower first page load than server-based applications. This is because the first load has to bring down the framework and the application code before rendering the required view as HTML in the browser. A server-based application just has to push out the required HTML to the browser, reducing the latency and download time.

Speeding up the page load

There are some ways of speeding up the initial load of an SPA, such as a heavy approach to caching and lazy-loading modules when you need them. But you’ll never get away from the fact that it needs to download the framework, at least some of the application code, and will most likely hit an API for data before displaying something in the browser.

Should you care about speed?

The answer to whether you should care about the speed of the initial page load is, once again, “it depends.” It depends on what you’re building and how people are going to interact with it.

Think about Gmail. Gmail is an SPA and takes quite a while to load. Granted this is only normally a couple of seconds, but everyone online is impatient these days and expects immediacy. But people don’t mind waiting for Gmail to load, as it’s snappy and responsive once you’re in. And once you’re in, you often stay in for a while.

But if you have a blog pulling in traffic from search engines and other external links, you don’t want the first page load to take a few seconds. People will assume your site is down or running slowly and click the back button before you’ve had the chance to show them content. I’m willing to bet that you know this happens because you’ve done it yourself!

2.2.4. To SPA or not to SPA?

Just a reminder that this wasn’t an exercise in SPA-bashing; we’re just taking a moment to think about some things that often get pushed to the side until it’s too late. The three points about crawlability, analytics integration, and page load speed aren’t designed to give clear-cut definitions about when to create an SPA and when to do something else. They’re there to give a framework for consideration.

It might be the case that none of those things is an issue for your project, and that an SPA is definitely the right way to go. If you find that each point makes you pause and think, and it looks like you need to add in workarounds for all three, then an SPA probably isn’t the way to go.

If you’re somewhere in between then it’s a judgment call about what is most important, and, crucially, what is the best solution for the project. As a rule of thumb, if your solution includes a load of workarounds at the outset then you probably need to rethink it.

Even if you decide that an SPA isn’t right for you, that doesn’t mean that you can’t use the MEAN stack. Let’s move on and take a look at how you can design a different architecture.

2.3. Designing a flexible MEAN architecture

If AngularJS is like having a Porsche then the rest of the stack is like also having an Audi RS6 in the garage. A lot of people may be focusing on your sports car out front and not give a second glance to the estate car in your garage. But if you do go into the garage and have a poke around, you’ll find that there’s a Lamborghini V10 engine under the hood. There’s a lot more to that estate car than you might first think!

Only ever using MongoDB, Express, and Node.js together to build a REST API is like only ever using the Audi RS6 to do the school drop-off runs. They’re all extremely capable and will do the job very well, but they have a lot more to offer.

We talked a little about what the technologies can do in chapter 1, but here are a few starting points:

  • MongoDB can store and stream binary information.
  • Node.js is particularly good for real-time connections using web sockets.
  • Express is a web application framework with templating, routing, and session management built in.

There’s also a lot more, and I’m certainly not going to be able to address the full capabilities of all of the technologies in this book. I’d need several books to do that! What I can do here is give you a simple example and show you how you can fit together the pieces of the MEAN stack to design the best solution.

2.3.1. Requirements for a blog engine

Let’s take a look at the familiar idea of a blog engine, and see how you could best architect the MEAN stack to build one.

A blog engine typically has two sides to it. There’s a public-facing side serving up articles to readers, and hopefully being syndicated and shared across the internet. A blog engine will also have an administrator interface where blog owners log in to write new articles and manage their blogs. Figure 2.2 shows some of the key characteristics for these two sides.

Figure 2.2. Conflicting characteristics of the two sides of a blog engine, the public-facing blog entries and the private admin interface

Looking at the lists in figure 2.2, it’s quite easy to see a high level of conflict between the characteristics of the two sides. You’ve got content-rich, low interaction for the blog articles, but a feature-rich, highly interactive environment for the admin interface. The blog articles should be quick to load to reduce bounce rates, whereas the admin area should be quick to respond to user input and actions. Finally, users typically stay on a blog entry for a short time, but may share it with others, whereas the admin interface is very private and an individual user could be logged in for a long time.

Taking what we’ve discussed about potential issues with SPAs, and looking at the characteristics of blog entries, you’ll see quite a lot of overlap. It’s quite likely that bearing this in mind you’d choose not to use an SPA to deliver your blog articles to readers. On the other hand, the admin interface is a perfect fit for an SPA.

So what do you do? Arguably the most important thing is to keep the blog readers coming—if they get a bad experience they won’t come back and they won’t share. If a blog doesn’t get readers then the writer will stop writing or move to another platform. Then again, a slow and unresponsive admin interface will also see your blog owners jumping ship. So what do you do? How do you keep everybody happy and keep the blog engine in business?

2.3.2. A blog engine architecture

The answer lies in not looking for a one-size-fits-all solution. You effectively have two applications. You have public-facing content that should be delivered direct from the server and an interactive private admin interface that you want to build as an SPA. Let’s start by looking at each of the two applications separately, starting with the admin interface.

Admin interface: An AngularJS SPA

We’ve already discussed that this would be an ideal fit for an SPA built in AngularJS. So the architecture for this part of the engine will look very familiar: a REST API built with MongoDB, Express, and Node.js with an AngularJS SPA upfront. Figure 2.3 shows how this looks.

Figure 2.3. A familiar sight: the admin interface would be an AngularJS SPA making use of a REST API built with MongoDB, Express, and Node.js

There’s nothing particularly new shown in figure 2.3. The entire application is built in AngularJS and runs in the browser, with JSON data being passed back and forth between the AngularJS application and the REST API.

Blog entries: What to do?

Looking at the blog entries, things get a little more difficult.

If you only think of the MEAN stack as an AngularJS SPA calling a REST API then you’re going to get a bit stuck. You could build the public-facing site as an SPA anyway, because you want to use JavaScript and the MEAN stack. But it’s not the best solution. You could decide that the MEAN stack isn’t appropriate in this case and choose a different technology stack. But you don’t want to do that! You want end-to-end JavaScript.

So let’s take another look at the MEAN stack, and think about all of the components. You know that Express is a web application framework. You know that Express can use template engines to build HTML on the server. You know that Express can use URL routing and MVC patterns. You should start to think that perhaps Express has the answer!

Blog entries: Making good use of Express

In this blog scenario, delivering the HTML and content directly from the server is exactly what you want to do. Express does this particularly well, even offering a choice of template engines right from the get-go. The HTML content will require data from the database, so you’ll use a REST API again for that (more on why it’s best to take this approach in section 2.3.3). Figure 2.4 lays out the basis for this architecture.

Figure 2.4. An architecture for delivering HTML directly from the server: an Express and Node.js application at the front, interacting with a REST API built in MongoDB, Express, and Node.js

This gives you an approach where you can use the MEAN stack, or part of it at least, to deliver database-driven content directly from the server to the browser. But it doesn’t have to stop there. The MEAN stack is yet again more flexible.

Blog entries: Using more of the stack

You’re looking at an Express application delivering the blog content to the visitors. If you want visitors to be able to log in, perhaps to add comments to articles, you need to track user sessions. You could use MongoDB with your Express application to do just this.

You might also have some dynamic data in the sidebar of your posts, such as related posts or a search box with type-ahead auto-completion. You could implement these in AngularJS. Remember, AngularJS isn’t only for SPAs; it can also be used to add some rich data interactivity to an otherwise static page.

Figure 2.5 shows these optional parts of MEAN added to the blog entry architecture.

Figure 2.5. Adding the options of using AngularJS and MongoDB as part of the public-facing aspect of the blog engine, serving the blog entries to visitors

Now you have the possibility of a full MEAN application delivering content to visitors interacting with your REST API.

Blog engine: A hybrid architecture

At this point there are two separate applications, each using a REST API. With a little bit of planning this can be a common REST API, used by both sides of the application.

Figure 2.6 shows what this looks like as a single architecture, with the one REST API interacting with the two front-end applications.

Figure 2.6. A hybrid MEAN stack architecture: a single REST API feeding two separate user-facing applications, built using different parts of the MEAN stack to give the most appropriate solution

This is just a simple example to show how you can piece together the various parts of the MEAN stack into different architectures to answer the questions that your projects ask of you. Your options are only limited by your understanding of the components and your creativity in putting them together. There’s no one correct architecture for the MEAN stack.

2.3.3. Best practice: Build an internal API for a data layer

You’ve probably noticed that every version of the architecture includes an API to surface the data, and allows interaction between the main application and the database. There’s a good reason for this.

If you were to start off by building your application in Node.js and Express, serving HTML directly from the server, it would be really easy to talk to the database directly from the Node.js application code. With a short-term view this is the easy way. But with a long-term view this becomes the difficult way, as it will tightly couple your data to your application code in a way that nothing else could use it.

The other option is to build your own API that can talk to the database directly and output the data you need. Your Node.js application can then talk with this API instead of directly with the database. Figure 2.7 shows a comparison of the two setups.

Figure 2.7. The short-term view of data integration into your Node.js application. You can set up your Node.js application to talk directly to your database, or you can create an API that interacts with the database and have your Node.js application talk only with the API.

Looking at figure 2.7 you could well be wondering why you’d want to go to the effort of creating an API just to sit in between your application and your database. Isn’t it creating more work? At this stage, yes, it’s creating more work—but you want to look further down the road here. What if you want to use your data in a native mobile application a little later? Or, for example, in an AngularJS front end?

You certainly don’t want to find yourself in the position where you have to write separate but similar interfaces for each. If you’ve built your own API upfront that outputs the data you need, you can avoid all of this. If you have an API in place, when you want to integrate the data layer into your application you can simply make it reference your API. It doesn’t matter if your application is Node.js, AngularJS, or iOS. It doesn’t have to be a public API that anyone can use, so long as you can access it. Figure 2.8 shows a comparison of the two approaches when you have Node.js, AngularJS, and iOS applications all using the same data source.

Figure 2.8. The long-term view of data integration into your Node.js application, and additional AngularJS and iOS applications. The integrated approach has now become fragmented, whereas the API approach is simple and maintainable.

As figure 2.8 shows, the previously simple integrated approach is now becoming fragmented and complex. You’ll have three data integrations to manage and maintain, so any changes will have to be made in multiple places to retain consistency. If you have a single API you don’t have any of these worries. So with a little bit of extra work at the beginning, you can make life much easier for yourself further down the road. We’ll look at creating internal APIs in chapter 6.

2.4. Planning a real application

As we talked about in chapter 1, throughout the course of this book we’ll build a working application on the MEAN stack called Loc8r. Loc8r will list nearby places with WiFi where people can go and get some work done. It will also display facilities, opening times, a rating, and a location map for each place. Visitors will be able to submit ratings and reviews.

For the sake of the demo application, we’ll be creating fake data so that we can test it quickly and easily. So let’s get planning.

2.4.1. Planning the application at a high level

The first step is to think about what screens we’ll need in our application. We’ll focus on the separate page views and the user journeys. We can do this at a very high level, not really concerning ourselves with the details of what is on each page. It is a good idea to sketch out this stage on a piece of paper or a whiteboard, as it helps to visualize the application as a whole. It also helps with organizing the screens into collections and flows, while serving as a good reference point for when we come to build it. As there’s no data attached to the pages or application logic behind them, it’s really easy to add and remove parts, change what is displayed where, and even change how many pages we want. The chances are that we won’t get it right the first time; the key is to start and iterate and improve until we’re happy with the separate pages and overall user flow.

Planning the screens

Let’s think about Loc8r. As stated our aim is as follows:

Loc8r will list nearby places with WiFi where people can go and get some work done. It will also display facilities, opening times, a rating, and a location map for each place. Visitors will be able to submit ratings and reviews.

From this we can get an idea about some of the screens we’re going to need:

  1. A screen that lists nearby places
  2. A screen that shows details about an individual place
  3. A screen for adding a review about a place

We’ll probably also want to tell visitors what Loc8r is for and why it exists, so we should add another screen to the list:

  1. A screen for “about us” information
Dividing the screens into collections

Next we want to take the list of screens and collate them where they logically belong together. For example, the first three in the list are all dealing with locations. The About page doesn’t really belong anywhere so it can go in a miscellaneous Others collection. Sketching this out brings us something like figure 2.9.

Figure 2.9. Collate the separate screens for our application into logical collections.

Having a quick sketch like this is the first stage in planning, and we really need to go through this stage before we can start thinking about architecture. This stage gives us a chance to look at the basic pages, and to also think about the flow. Figure 2.9, for example, also shows a basic user journey in the Locations collection, going from the List page, to a Details page, and then onto the form to add a review.

2.4.2. Architecting the application

On the face of it Loc8r is a fairly simple application, with just a few screens. But we still need to think about how to architect it, as we’re going to be transferring data from a database to a browser, letting users interact with the data, and allowing data to be sent back to the database.

Starting with the API

Because the application is going to be using a database and passing data around, we’ll start building up the architecture with the piece we’re definitely going to need. Figure 2.10 shows the starting point, a REST API built with Express and Node.js to enable interactions with the MongoDB database.

Figure 2.10. Start with the standard MEAN REST API, using MongoDB, Express, and Node.js.

As already discussed in this chapter, building an API to interface with our data is a bit of a given, and is the base point of the architecture. So the more interesting and difficult question is: How do we architect the application itself?

Application architecture options

At this point we need to take a look at the specific requirements of our application, and how we can put together the pieces of the MEAN stack to build the best solution. Do we need something special from MongoDB, Express, AngularJS, or Node.js that will swing the decision a certain way? Do we want HTML served directly from the server, or is an SPA the better option?

For Loc8r there are no unusual or specific requirements, and whether or not it should be easily crawlable by search engines depends on the business growth plan. If the aim is to bring in organic traffic from search engines, then yes it needs to be crawlable. If the aim is to promote the application as an application and drive use that way, then search engine visibility is a lesser concern.

Thinking back to the blog example, we can immediately envisage three possible application architectures as shown in figure 2.11:

Figure 2.11. Three options for building the Loc8r application, ranging from a server-side Express and Node.js application to a full client-side AngularJS SPA

  1. A Node.js and Express application
  2. A Node.js and Express application with AngularJS additions for interactivity
  3. An AngularJS SPA

With these three options in mind, which is the best for Loc8r?

Choosing an application architecture

There are no specific business requirements pushing us to favor one particular architecture over another. It doesn’t matter because we’re going to do all three in this book. Building all three of the architectures will allow us to explore how each approach works, and will enable us to take a look at each of the technologies in turn, building up the application layer by layer.

We’ll be building the architectures in the order they’re shown in figure 2.11, starting with a Node.js and Express application, then moving on to add some AngularJS, before refactoring to an AngularJS SPA. While this isn’t necessarily how you might build a site normally, it gives you a great opportunity for learning all aspects of the MEAN stack. We’ll talk shortly in section 2.5 about the approach, and walk through the plan in a bit more detail.

2.4.3. Wrapping everything in an Express project

The architecture diagrams we’ve been looking at so far imply that we’ll have separate Express applications for the API and the application logic. This is perfectly possible, and is a good way to go for a large project. If we’re expecting large amounts of traffic we might even want our main application and our API on different servers. An additional benefit of this is that we can have more specific settings for each of the servers and applications that are best suited to the individual needs.

Another way is to keep things simple and contained and have everything inside a single Express project. With this approach we only have one application to worry about hosting and deploying, and one set of source code to manage. This is what we’ll be doing with Loc8r, giving us one Express project containing a few subapplications. Figure 2.12 illustrates this particular approach.

Figure 2.12. The architecture of the application with the API and application logic wrapped inside the same Express project

When putting together an application in this way it’s important to organize our code well so that the distinct parts of the application are kept separate. As well as making our code easier to maintain, it also makes it easier to split it out into separate projects further down the line if we decide that’s the right route. This is a key theme that we’ll keep coming back to throughout the book.

2.4.4. The end product

As you can see, we’ll use all layers of the MEAN stack to create Loc8r. We’ll also include Twitter Bootstrap to help us create a responsive layout. Figure 2.13 shows some screenshots of what we’re going to be building throughout the book.

Figure 2.13. Loc8r is the application we’re going to build throughout this book. It will display differently on different devices, showing a list of places and details about each place, and will enable visitors to log in and leave reviews.

2.5. Breaking the development into stages

In this book we have two aims:

  1. Build an application on the MEAN stack
  2. Learn about the different layers of the stack as we go

We’ll approach the project in the way I’d personally go about building a rapid prototype, but with a few tweaks to give you the best coverage of the whole stack. We’ll start by looking at the five stages of rapid prototype development, and then see how we can use this approach to build up Loc8r layer by layer, focusing on the different technologies as we go.

2.5.1. Rapid prototype development stages

Let’s break down the process into a number of stages, which lets us concentrate on one thing at a time, increasing our chances of success. I find this approach works well for making an idea a reality.

Stage 1: Build a static site

The first stage is to build a static version of the application, which is essentially a number of HTML screens. The aims of this stage are

  • To quickly figure out the layout
  • To ensure that the user flow makes sense

At this point we’re not concerned with a database or flashy effects on the user interface; all we want to do is create a working mockup of the main screens and journeys that a user will take through the application.

Stage 2: Design the data model and create the database

Once we have a working static prototype that we’re happy with, the next thing to do is look at any hard-coded data in the static application and put it into a database. The aims of this stage are

  • To define a data model that reflects the requirements of the application
  • To create a database to work with the model

The first part of this is to define the data model. Stepping back to a bird’s-eye view, what are the objects we need data about, how are the objects connected, and what data is held in them?

If we try to do this stage before building the static prototype then we’re dealing with abstract concepts and ideas. Once we have a prototype, we can see what is happening on different pages and what data is needed where. Suddenly this stage becomes much easier. Almost unknown to us, we’ve done the hard thinking while building the static prototype.

Stage 3: Build our data API

After stages 1 and 2 we have a static site on one hand and a database on the other. This stage and the next take the natural steps of linking them together. The aim of stage 3 is

  • To create a REST API that will allow our application to interact with the database
Stage 4: Hook the database into the application

When we get to this stage we have a static application and an API exposing an interface to our database. The aim of this stage is

  • To get our application to talk to our API

When this stage is complete the application will look pretty much the same as it did before, but the data will be coming from the database. When it’s done, we’ll have a data-driven application!

Stage 5: Augment the application

This stage is all about embellishing the application with additional functionality. We might add authentication systems, data validation, or methods for displaying error messages to users. It could include adding more interactivity to the front end or tightening up the business logic in the application itself.

So, really, the aims of this stage are

  • To add finishing touches to our application
  • To get the application ready for people to use

These five stages of development provide a great methodology for approaching a new build project. Let’s take a look at how we’ll follow these steps to build Loc8r.

2.5.2. The steps to build Loc8r

In building Loc8r throughout this book we have two aims. First, of course, we want to build a working application on the MEAN stack. Second, we want to learn about the different technologies, how to use them, and how to put them together in different ways.

So throughout the book we’ll be following the five stages of development, but with a couple of twists so that we get to see the whole stack in action. Before we look at the steps in detail, let’s quickly remind ourselves of the proposed architecture as shown in figure 2.14.

Figure 2.14. Proposed architecture for Loc8r as we’ll build it throughout this book

Step 1: Build a static site

We’ll start off by following stage 1 and building a static site. I recommend doing this for any application or site, as you can learn a lot with relatively little effort. When building the static site, it’s good to keep one eye on the future, keeping in mind what the final architecture will be. We’ve already defined the architecture for Loc8r as shown in figure 2.14.

Based on this architecture we’ll build the static application in Node and Express, using that as our starting point into the MEAN stack. Figure 2.15 highlights this step in the process as the first part of developing the proposed architecture.

Figure 2.15. The starting point for our application is building the user interface in Express and Node.js.

This step is covered in chapters 3 and 4.

Step 2: Design the data model and create the database

Still following the stages of development we’ll continue to stage 2 by creating the database and designing the data model. Again, any application is likely to need this step, and you’ll get much more out of it if you’ve been through step 1 first.

Figure 2.16 illustrates how this step adds to the overall picture of building up the application architecture.

Figure 2.16. After the static site is built we’ll use the information gleaned to design the data model and create the MongoDB database.

In the MEAN stack we’ll use MongoDB for this step, relying heavily on Mongoose for the data modeling. The data models themselves will actually be defined inside the Express application. This step will be covered in chapter 5.

Step 3: Build our REST API

When we’ve built the database and defined the data models we’ll want to create a REST API so that we can interact with the data through making web calls. Pretty much any data-driven application will benefit from having an API interface, so this is another step you’ll want to have in most build projects.

You can see where this step fits into building the overall project in figure 2.17.

Figure 2.17. Use Express and Node.js to build an API, exposing methods of interacting with the database.

In the MEAN stack this step is mainly done in Node.js and Express, with quite a bit of help from Mongoose. We’ll use Mongoose to interface with MongoDB rather than dealing with MongoDB directly. This step will be covered in chapter 6.

Step 4: Use the API from our application

This step matches stage 4 of the development process and is where Loc8r will start to come to life. The static application from step 1 will be updated to use the REST API from step 3 to interact with the database created in step 2.

To learn about all parts of the stack, and the different ways in which we can use them, we’ll be using Express and Node.js to make calls to the API. If, in a real-world scenario, you were planning to build the bulk of an application in AngularJS then you’d hook your database into AngularJS instead. We’ll cover that in chapters 8, 9, and 10.

At the end of this step we’ll have an application running on the first of the three architectures: an Express and Node.js application. Figure 2.18 shows how this step fits together the two sides of the architecture.

Figure 2.18. Update the static Express application by hooking it into the data API, allowing the application to be database-driven.

In this build we’ll be doing the majority of this step in Node.js and Express, and it will be covered in chapter 7.

Step 5: Embellish the application

Step 5 relates to stage 5 in the development process where we get to add extra touches to the application. We’re going to use this step to take a look at AngularJS, and we’ll see how we can integrate AngularJS components into an Express application.

You can see this addition to the project architecture highlighted in figure 2.19.

Figure 2.19. One way to use AngularJS in a MEAN application is to add components to the front end in an Express application.

This step is all about introducing and using AngularJS. To support this we’ll most likely also change some of our Node.js and Express setup. This step will be covered in chapter 8.

Step 6: Refactor the code into an AngularJS SPA

In step 6 we’ll radically change the architecture by replacing the Express application and moving all of the logic into an SPA using AngularJS. Unlike all of the previous steps, this replaces some of what has come before it, rather than building upon it.

This would be an unusual step in a normal build process, to develop an application in Express and then redo it in AngularJS, but it suits the learning approach in this book particularly well. We’ll be able to focus on AngularJS as we already know what the application should do, and there’s a data API ready for us.

Figure 2.20 shows how this change affects the overall architecture.

Figure 2.20. Effectively rewriting the application as an AngularJS SPA

This step is once again focused on AngularJS, and will be covered in chapters 9 and 10.

Step 7: Add authentication

In step 7 we’ll add functionality to the application and enable users to register and log in, and also see how to make use of the user’s data whilst they are using the application. We’ll build on everything we’ve done so far and add authentication to the Angular SPA. As a part of this we’ll save user information in the database and secure certain API end points so that they can only be used by authenticated users.

Figure 2.21 shows what we’ll be working with in the architecture.

Figure 2.21. Using all of the MEAN stack to add authentication to the AngularJS SPA

In this step we’ll work with all of the MEAN technologies; this is covered in chapter 11.

2.6. Hardware architecture

No discussion about architecture would be complete without a section on hardware. You’ve seen how all of the software and code components can be put together, but what type of hardware do you need to run it all?

2.6.1. Development hardware

The good news is that you don’t need anything particularly special to run a development stack. Just a single laptop, or even a virtual machine (VM), is enough to develop a MEAN application. All components of the stack can be installed on Windows, Mac OS X, and most Linux distributions.

I’ve successfully developed applications on Windows and Mac OS X laptops, and also on Ubuntu VMs. My personal preference is native development in OS X, but I know of others who swear by using Linux VMs.

If you have a local network and a number of different servers you can run different parts of your application across them. For example, it’s possible to have one machine as a database server, another for the REST API, and a third for the main application code itself. So long as the servers can talk to each other this isn’t a problem.

2.6.2. Production hardware

The approach to production hardware architecture isn’t all that different from development hardware. The main difference is that production hardware is normally higher spec, and is open to the internet to receive public requests.

Starter size

It’s quite possible to have all parts of your application hosted and running on the same server. You can see a basic diagram of this in figure 2.22.

Figure 2.22. The simplest of hardware architectures, having everything on a single server

This architecture is okay for applications with low amounts of traffic, but isn’t generally advised as your application grows, because you don’t want your application and database fighting over the same resources.

Growing up: A separate database server

One of the first things to be moved onto a separate server is often the database. So now you have two servers: one for the application code and one for the database. Figure 2.23 illustrates this approach.

Figure 2.23. A common hardware architecture approach: one server to run the application code and API, and a second, separate database server

This is quite a common model, particularly if you choose to use a platform as a service (PaaS) provider for your hosting. We’ll be using this approach in this book.

Going for scale

Much like we talked about in the development hardware, you can have a different server for the different parts of your application—a database server, an API server, and an application server. This will allow you to deal with more traffic as the load is spread across three servers, as illustrated in figure 2.24.

Figure 2.24. A decoupled architecture using three servers: one for the database, one for the API, and one for the application code

But it doesn’t stop there. If your traffic starts to overload your three servers, you can have multiple instances—or clusters—of these servers, as shown in figure 2.25.

Figure 2.25. You can scale MEAN applications by having clusters of servers for each part of your entire application.

Setting up this approach is a little more involved than the previous methods because you need to ensure that your database remains accurate, and that the load is balanced across the servers. Once again, PaaS providers offer a convenient route into this type of architecture.

2.7. Summary

In this chapter we’ve covered

  • A common MEAN stack architecture with an AngularJS SPA using a REST API built in Node.js, Express, and Mongo
  • Points to consider when deciding whether to build an SPA or not
  • How to design a flexible architecture in the MEAN stack
  • The best practice of building an API to expose a data layer
  • The steps we’re going to take to build the sample application Loc8r
  • Development and production hardware architectures

We’ll get started on the journey in chapter 3 by creating the Express project that will hold everything together.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.22.169