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
€18.99 per month
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
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Eddy Wilson Iriarte Koroliova
Arrow right icon
€18.99 per month
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
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781787281080
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
€18.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
€189.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
€264.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 98.97
React Cookbook
€36.99
MERN Quick Start Guide
€24.99
Full-Stack React Projects
€36.99
Total 98.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.