# Build Web Applications Using Node.js

Aside from building APIs, Node.js is great for building standard web applications. It has powerful tools to meet the needs of web developers. In this tutorial, you will be building a web application that can serve as a local library.

While building, you will learn about some types of middleware, you will see how to handle form submission in Node.js, and you will also be able to reference two models.

Let's get started.

## Getting Started

Start by installing the express generator on your machine.

Run the express generator command to generate your application.

Now migrate into your working folder, open package.json, and make the dependencies similar to what I have below.

Run the command to install the packages.

## Set Up the Entry File

The app.js file was created when you ran the generator command; however, you need to do some extra configuration. Edit the file to look like what I have below. I'll go through the file and explain the changes as we go.

Require the two routes for the app. You will create the routes file shortly. The required routes are assigned as values to two different variables which are used when setting up the middleware for your routes.

Next, set Mongoose to use global.Promise. The MongoDB variable is assigned the MONGODB_URI of your environment or the path to your local mongo server. This variable is passed as an argument to connect to the running MongoDB server.

Set up session middleware using express-session. This middleware is important as you will be displaying flash messages in some parts of your application.

Set up middleware for validation. This middleware will be used to validate form input, ensuring that users of the application do not submit an empty form. The validation uses express-validator.

Set up middleware which will come in handy when displaying flash messages. This middleware uses connect-flash.

The routes for the application are set up to use the routes file you required. Requests pointing to /genres and /books will use the genres and books routes files respectively. At this moment, you have not created the routes files, but you will do that soon.

Note that this code was converted to ESM, as the generator only generates CommonJS.

### What Is ESM and Why Are There import Statements?

ESM (ECMAScript Modules) is a next-generation module format for JavaScript on the web and Node.js. It replaces CommonJS, an old module format used in Node.js that you likely have seen (it uses require() and module.exports). ESM supports new features like asynchronous module loading, tree shaking, and support on the web. Going forward, ESM will slowly replace CommonJS (and already has for many new applications), so in this tutorial, we will be using ESM. There are import statements because that is how you import packages using ESM.

Another thing you need to do is edit /bin/www to use ESM.

Finally, delete the auto-generated routes files (index.js and user.js).

## Book and Genre Model

The Book Model will make use of Mongoose Schema to define how the books will be structured. Create a directory called models and a new file called book.js. Here is what it looks like.

Here you have four fields. The last field is used to store the genre each book belongs to. The genre field here references the Genre model, which will be created next. That's why the type is set to Schema.Types.ObjectId, which is where the ids of each referenced genre will be saved. ref specifies the model you are referencing. Note that the genre is saved as an array, meaning that a book can have more than one genre.

Let's go ahead and create the Genre model in models/genre.js.

For your Genre, you need just one field: name.

## Genre Index Route and View

For this tutorial, you will make use of two routes paths for your genre: a path to add new genres, and another that lists the genres you have. Create a file in your routes directory called genres.js.

Start by requiring all the modules you will be using.

Next, drop in the route that handles the index file for your genres.

This route gets called whenever requests are made to /genres. Here you call the find method on your Genre model to obtain all the genres that have been created. These genres are then rendered on a template called genres. Let's go ahead and create that, but first, update your layout.pug to look like this:

This will give your views a nice structure to aid navigation. Now create a view file called genre.pug. In this file, you will loop through the genres created and output each genre in an unordered list.

Here is how the file should look.

## Add New Genre Routes and View

Go back to your routes/genres.js file to add the routes that will handle the creation of new genres.

The job of this router is to simply display the page for adding new routes. This router gets called whenever requests are made to the /genres/add path.

This router handles the submission of the form. When the form is submitted, we check to ensure that the user has entered a name. If no name is entered, the page is rendered again. If the checks are good to go, the genre is saved and the user is redirected to the /genres page.

The module is exported as a router.

## Books Routes and View

Create a new route file for books, and name it books.js. As you did earlier with the genre, start by requiring the necessary modules.

Next, set up the router for displaying all the books saved in the library. Try that on your own in the same way you set up that of the genre; you can always check back to make corrections.

I guess you tried that out—here is how it should look.

When this router is called, a request is made to find all books saved in the database. If all goes well, the books are shown on the /books page, else an error is thrown.

You need to create a new file for displaying all books, views/books.pug, and here is how it should look.

You simply loop through the books returned and output the name and description of each book using an unordered list. The name of the book points to the individual page of the book.

## Add New Book Routes and View

The next router you set up will handle the addition of new books. Two routers will be used here: one will simply render the page, and another will handle the submission of the form.

This is how the routers look.

In the first router, you are displaying the /addBooks page. This router is called when a request is made to the /add path. Since books added are supposed to have genres, you want to display the genres that have been saved to the database.

The code above finds all the genres in your database and returns them in the variable genres. With this, you will be able to loop through the genres and display them as checkboxes.

The second router handles the submission of the form. First, you check the body of the request to ensure that some fields are not empty. This is where the express-validator middleware you set in app.js comes in handy. If there are errors, the page is rendered again. If there are none, the new Book instance is saved and the user is redirected to the /books page.

Let's go ahead and create the views for this.

Create a new view file called addBooks.pug. Note that the name of the view matches the first parameter given to res.render. This is because you are rendering a template. During redirection, you simply pass the path you want to redirect to, as you did with res.redirect('/books').

Having established that, here is what the views should look like in views/addGenre.pug.

The important thing to note here is the form action and method. When the submit button is clicked, you are making a POST request to /books/add. One other thing—once again you loop through the collection of genres returned and display each of them.

## Book Show Route and View

Let us drop in the route to handle the requests made to each books page in routes.books.js. While you are there, it is important to export your module too.

No magic is happening here.

First, requests made to this router must have an id: the id of the book. This id is obtained from the params of the request using req.params.id. This is used to identify the specific book that should be obtained from the database, as the ids are unique. When the book is found, the genre value of the book is populated with all the genres that have been saved to this book instance. If all goes well, the book view is rendered, else an error is thrown.

Let's create the view for a book. Here is how it should look.

You can start up your node server by running:

## Conclusion

Now you know how to build a standard web application in Node.js, not just a simple to-do app. You were able to handle form submission, reference two models, and set up some middleware. The full example code is here.

You can go further by extending the application—try adding the ability to delete a book. First add a button to the show page, and then go to the routes files and add a router for this. Note that this is going to be a POST request.

You can also think of more features to add to the application. I hope you enjoyed it.

This post has been updated with contributions from Jacob Jackson. Jacob is a web developer, technical writer, freelancer, and open-source contributor.