Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
MERN Quick Start Guide
MERN Quick Start Guide

MERN Quick Start Guide: Build web applications with MongoDB, Express.js, React, and Node

Arrow left icon
Profile Icon Eddy Wilson Iriarte Koroliova
Arrow right icon
Mex$378.99 Mex$541.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7 (6 Ratings)
eBook May 2018 302 pages 1st Edition
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
Arrow left icon
Profile Icon Eddy Wilson Iriarte Koroliova
Arrow right icon
Mex$378.99 Mex$541.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7 (6 Ratings)
eBook May 2018 302 pages 1st Edition
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

MERN Quick Start Guide

Building a Web server with ExpressJS

In this chapter, we will cover the following recipes:

  • Routing in ExpressJS
  • Modular route handlers
  • Writing middleware functions
  • Writing configurable middleware functions
  • Writing router-level middleware functions
  • Writing error-handler middleware functions
  • Using ExpressJS' built-in middleware function to serve static assets
  • Parsing the HTTP request body
  • Compressing HTTP responses
  • Using an HTTP request logger
  • Managing and creating virtual domains
  • Securing an ExpressJS web application with helmet
  • Using template engines
  • Debugging your ExpressJS web application

Technical requirements

Introduction

ExpressJS is the preferred de facto Node.js web application framework for building robust web applications and APIs.

In this chapter, the recipes will focus on building a fully functional web server and understanding the core fundamentals.

Routing in ExpressJS

Routing refers to how an application responds or acts when a resource is requested via an HTTP verb or HTTP method.

HTTP stands for Hypertext Transfer Protocol and it's the basis of data communication for the World Wide Web (WWW). All documents and data in the WWW are identified by a Uniform Resource Locator (URL).

HTTP verbs or HTTP methods are a client-server model. Typically, a web browser serves as a client, and in our case ExpressJS is the framework that allows us to create a server capable of understanding these requests. Every request expects a response to be sent to the client to recognize the status of the resource that it is requesting.

Request methods can be:

  • Safe: An HTTP verb that performs read-only operations on the server. In other words, it does not alter the server state. For example: GET.
  • Idempotent: An HTTP verb that has the same effect...

Modular route handlers

ExpressJS has a built-in class called router. A router is just a class that allows developers to write mountable and modular route handlers.

A Router is an instance of ExpressJS' core routing system. That means, all routing methods from an ExpressJS application are available:

const router = express.Router() 
router.get('/', (request, response, next) => { 
  response.send('Hello there!') 
}) 
router.post('/', (request, response, next) => { 
  response.send('I got your data!') 
}) 

Getting ready

In this recipe, we will see how to use a router to make a modular application. Before you start, create a new package.json file with the following content:

{ ...

Writing middleware functions

Middleware functions are mainly used to make changes in the request and response object. They are executed in sequence, one after another, but if a middleware functions does not pass control to the next one, the request is left hanging.

Getting ready

Middleware functions have the following signature:

app.use((request, response, next) => { 
    next() 
}) 

The signature is very similar to writing route handlers. In fact, a middleware function can be written for a specific HTTP method and a specific path route, and will look like this, for example:

app.get('/', (request, response, next) => { 
    next() 
}) 

So, if you are wondering what the difference is between route handlers, and...

Writing configurable middleware functions

A common pattern for writing middleware functions is to wrap the middleware function inside another function. The result of doing so is a configurable middleware function. They are also higher-order functions, that is, a function that returns another function.

const fn = (options) => (response, request, next) => {  
    next()  
} 

Usually an object is used as an options parameters. However, there is nothing stopping you from doing it in your own way.

Getting ready

In this recipe, you will write a configurable logger middleware function. Before you start, create a new package.json file with the following content:

{ 
    "dependencies": { 
        "express&quot...

Writing router-level middleware functions

Router-level middleware functions are only executed inside a router. They are usually used when applying a middleware to a mount point only or to a specific path.

Getting ready

In this recipe, you will create a small logger router-level middleware function that will only log requests to paths mounted or located in the router's mounted path. Before you start, create a new package.json file with the following content:

{ 
    "dependencies": { 
        "express": "4.16.3" 
    } 
} 

Then, install the dependencies by opening a Terminal and running:

npm install
...

Writing error-handler middleware functions

ExpressJS already includes by default a built-in error handler which gets executed at the end of all middleware and route handlers.

There are ways that the built-in error handler can be triggered. One is implicit when an error occurs inside a route handler. For example:

app.get('/', (request, response, next) => { 
    throw new Error('Oh no!, something went wrong!') 
}) 

And another way of triggering the built-in error handler is explicit when passing an error as an argument to next(error). For instance:

app.get('/', (request, response, next) => { 
    try { 
        throw new Error('Oh no!, something went wrong!') 
    } catch (error) { 
        next(error) 
    } 
}) 
The stack trace is displayed on the client side. If NODE_ENV is set to production, then the stack trace is not included.
...

Using ExpressJS' built-in middleware function for serving static assets

Prior to the 4.x version of ExpressJS, it has depended on ConnectJS which is an HTTP server framework https://github.com/senchalabs/connect. In fact, most middleware written for ConnectJS is also supported in ExpressJS.

As from the 4.x version of ExpressJS, it no longer depends on ConnectJS, and all previously built-in middleware functions were moved to separate modules https://expressjs.com/en/resources/middleware.html.

ExpressJS 4.x and newer versions include only two built-in middleware functions. The first one has already been seen: the built-in error handler middleware function. The second one is the express.static middleware function that is responsible for serving static assets.

The express.static middleware function is based on serve-static module https://expressjs.com/en/resources/middleware...

Parsing the HTTP request body

body-parser is a middleware function that parses the incoming request body and makes it available in the request object as request.body https://expressjs.com/en/resources/middleware/body-parser.html.

This module allows an application to parse the incoming request as:

  • JSON
  • Text
  • Raw (buffer original incoming data)
  • URL encoded form

The module supports automatic decompression of gzip and deflates encodings when the incoming request is compressed.

Getting ready

In this recipe, you will see how to use the body-parser NPM module to parse the content body sent from two different forms encoded in two different ways. Before you start, create a new package.json file with the following content:

{ 
    ...

Compressing HTTP responses

compression is a middleware function that compresses the response body that will be send to the client. This module uses the zlib module https://nodejs.org/api/zlib.html that supports the following content-encoding mechanisms:

  • gzip
  • deflate

The Accept-Encoding HTTP header is used to determine which content-encoding mechanism is supported on the client-side (for example web browser) while the Content-Encoding HTTP header is used to tell the client which content encoding mechanism was applied to the response body.

compression is a configurable middleware function. It accepts an options object as the first argument to define a specific behavior for the middleware and also to pass zlib options as well.

Getting ready

...

Using an HTTP request logger

As previously seen, writing a request logger is simple. However, writing our own could take precious time. Luckily, there are several other alternatives out there. For example, a very popular HTTP request logger widely used is morgan https://expressjs.com/en/resources/middleware/morgan.html.

morgan is a configurable middleware function that takes two arguments format and options which are used to specify the format in which the logs are displayed and what kind of information needs to be displayed.

There are several predefined formats:

  • tiny: Minimal output
  • short: Same as tiny, including remote IP address
  • common: Standard Apache log output
  • combined: Standard Apache combined log output
  • dev: Displays the same information as the tiny format does. However, the response statuses are colored.
...

Managing and creating virtual domains

Managing virtual domains is really easy with ExpressJS. Imagine that you have two or more subdomains, and you want to serve two different web applications. However, you do not want to create a different web server application for each subdomain. In this kind of situation, ExpressJS allows developers to manage virtual domains within a single web server application using vhost https://expressjs.com/en/resources/middleware/vhost.html.

vhost is a configurable middleware function that accepts two arguments. The first one is the hostname. The second argument is the request handler which will be called when the hostname matches.

The hostname follows the same rules as route paths do. They can be either a string or a regular expression.

Getting ready

...

Securing an ExpressJS web application with Helmet

Helmet allows to protect web server applications against common attacks, such as cross-site scripting (XSS), insecure requests, and clickjacking.

Helmet is a collection of 12 middleware functions that allow you to set specific HTTP headers:

  1. Content Security Policy (CSP): This is an effective way to whitelist what kind of external resources are allowed in your web application, such as JavaScript, CSS, and images, for instance.
  2. Certificate Transparency: This is a way of providing more transparency for certificates issued for a specific domain or specific domains https://sites.google.com/a/chromium.org/dev/Home/chromium-security/certificate-transparency.
  3. DNS Prefetch Control: This tells the browser if it should perform domain name resolution (DNS) on resources that are not yet loaded, such as links.
  4. Frameguard: This helps to prevent...

Using template engines

Template engines allow you to generate HTML code in a more convenient way. Templates or views can be written in any format, interpreted by a template engine that will replace variables with other values, and finally transform to HTML.

A big list of template engines that work out of the box with ExpressJS, is available in the official website at https://github.com/expressjs/express/wiki#template-engines.

Getting ready

In this recipe, you will build your own template engine. To develop and use your own template engine, you will first need to register it, then define the path where the views are located, and finally tell ExpressJS which template engine to use.

      app.engine('...', (path, options...

Debugging your ExpressJS web application

Debugging information on ExpressJS about all of the cycle of a web application is something simple. ExpressJS uses the debug NPM module internally to log information. Unlike console.log, debug logs can easily be disabled on production mode.

Getting ready

In this recipe, you will see how to debug your ExpressJS web application. Before you start, create a new package.json file with the following content:

{ 
    "dependencies": { 
        "debug": "3.1.0", 
        "express": "4.16.3" 
    } 
} 

Then, install the dependencies by opening a terminal and running:

npm install
...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Build applications with the MERN stack
  • • Work with each component of the MERN stack
  • • Become confident with MERN and ready for more!

Description

The MERN stack is a collection of great tools—MongoDB, Express.js, React, and Node—that provide a strong base for a developer to build easily maintainable web applications. With each of them a JavaScript or JavaScript-based technology, having a shared programming language means it takes less time to develop web applications. This book focuses on providing key tasks that can help you get started, learn, understand, and build full-stack web applications. It walks you through the process of installing all the requirements and project setup to build client-side React web applications, managing synchronous and asynchronous data flows with Redux, and building real-time web applications with Socket.IO, RESTful APIs, and other concepts. This book gives you practical and clear hands-on experience so you can begin building a full-stack MERN web application. Quick Start Guides are focused, shorter titles that provide a faster paced introduction to a technology. They are for people who don't need all the detail at this point in their learning curve. The presentation has been streamlined to concentrate on the things you really need to know.

Who is this book for?

The book is for JavaScript developers who want to get stated with the MERN Stack.

What you will learn

  • • Get started with the MERN stack
  • • Install Node.js and configure MongoDB
  • • Build RESTful APIs with Express.js and Mongoose
  • • Build real-time applications with Socket.IO
  • • Manage synchronous and asynchronous data flows with Redux
  • • Build web applications with React

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2018
Length: 302 pages
Edition : 1st
Language : English
ISBN-13 : 9781787280045
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : May 31, 2018
Length: 302 pages
Edition : 1st
Language : English
ISBN-13 : 9781787280045
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 2,686.97
React Cookbook
Mex$1004.99
MERN Quick Start Guide
Mex$676.99
Full-Stack React Projects
Mex$1004.99
Total Mex$ 2,686.97 Stars icon

Table of Contents

7 Chapters
Introduction to the MERN Stack Chevron down icon Chevron up icon
Building a Web server with ExpressJS Chevron down icon Chevron up icon
Building a RESTful API Chevron down icon Chevron up icon
Real-Time Communication with Socket.IO and ExpressJS Chevron down icon Chevron up icon
Managing State with Redux Chevron down icon Chevron up icon
Building Web Applications with React Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7
(6 Ratings)
5 star 33.3%
4 star 0%
3 star 16.7%
2 star 0%
1 star 50%
Filter icon Filter
Top Reviews

Filter reviews by




Alina Jun 21, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It's helpful and up-to-date
Amazon Verified review Amazon
ps Feb 09, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I like this book as it does not go into too much details and cause distraction from the topic. It's the best book for fast paced learning. Off course you can google the stuff you are unable to grasp or want more information. As the name suggest - Its and MERN quick start guide.
Amazon Verified review Amazon
Gustavo Adolfo Feb 23, 2024
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
the version of mongoose is outdated and you have to research if you want to make it works
Subscriber review Packt
Jonathan Garcia Mar 06, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Waste of money and time. Free instructions online are better than the content of this book. Save your time and money.
Amazon Verified review Amazon
Durga Srinivas Sep 12, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Don't buy kindle edition
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.