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
$32.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7 (6 Ratings)
Paperback May 2018 302 pages 1st Edition
eBook
$17.99 $25.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Eddy Wilson Iriarte Koroliova
Arrow right icon
$32.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7 (6 Ratings)
Paperback May 2018 302 pages 1st Edition
eBook
$17.99 $25.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$17.99 $25.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 : 9781787281080
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : May 31, 2018
Length: 302 pages
Edition : 1st
Language : English
ISBN-13 : 9781787281080
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 130.97
React Cookbook
$48.99
MERN Quick Start Guide
$32.99
Full-Stack React Projects
$48.99
Total $ 130.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

Most Recent
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
Most Recent

Filter reviews by




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
Cliente Kindle Dec 28, 2023
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
O conteúdo do livro é muito ruim, zero didático e com diversos erros para compilação dos códigos. E não consigo realizar a devolução, mesmo tendo comprado há 2 dias apenas.
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
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
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
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela