0% found this document useful (0 votes)
3 views80 pages

Mern Projects For Beginners Create Five Social Web Apps Using Mongodb Expressjs React and Node 1st Edition Nabendu Biswas PDF Download

The document is a guide for beginners to create five social web applications using the MERN stack, which includes MongoDB, Express.js, React, and Node.js. It covers the deployment setup, building various types of applications such as a dating app, short video app, messaging app, and photo-based social network, along with detailed instructions for each step. The book is authored by Nabendu Biswas and includes additional resources and supplementary materials available on GitHub.

Uploaded by

bohunzroudi22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views80 pages

Mern Projects For Beginners Create Five Social Web Apps Using Mongodb Expressjs React and Node 1st Edition Nabendu Biswas PDF Download

The document is a guide for beginners to create five social web applications using the MERN stack, which includes MongoDB, Express.js, React, and Node.js. It covers the deployment setup, building various types of applications such as a dating app, short video app, messaging app, and photo-based social network, along with detailed instructions for each step. The book is authored by Nabendu Biswas and includes additional resources and supplementary materials available on GitHub.

Uploaded by

bohunzroudi22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Mern Projects For Beginners Create Five Social

Web Apps Using Mongodb Expressjs React And Node


1st Edition Nabendu Biswas download

https://ebookbell.com/product/mern-projects-for-beginners-create-
five-social-web-apps-using-mongodb-expressjs-react-and-node-1st-
edition-nabendu-biswas-34674416

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Six Sigmalean Toolset Mindset For Successful Implementation Of


Improvement Projects 2nd Edition Renata Meran

https://ebookbell.com/product/six-sigmalean-toolset-mindset-for-
successful-implementation-of-improvement-projects-2nd-edition-renata-
meran-4269708

Project Management For Mere Mortalsr 1st Edition Claudia M Baca

https://ebookbell.com/product/project-management-for-mere-
mortalsr-1st-edition-claudia-m-baca-2204634

Project Management For Mere Mortals Baca Claudia M

https://ebookbell.com/product/project-management-for-mere-mortals-
baca-claudia-m-22124150

Project Management For Mere Mortals Claudia Baca

https://ebookbell.com/product/project-management-for-mere-mortals-
claudia-baca-57135430
Classic Hairstyles For Men An Illustrated Guide To Mens Hair Style
Hair Care Hair Products Antonio Centeno Geoffrey Cubbage Centeno

https://ebookbell.com/product/classic-hairstyles-for-men-an-
illustrated-guide-to-mens-hair-style-hair-care-hair-products-antonio-
centeno-geoffrey-cubbage-centeno-23830100

Classic Hairstyles For Men An Illustrated Guide To Mens Hair Style


Hair Care Hair Products Centeno

https://ebookbell.com/product/classic-hairstyles-for-men-an-
illustrated-guide-to-mens-hair-style-hair-care-hair-products-
centeno-6626900

Classic Hairstyles For Men An Illustrated Guide To Mens Hair Style


Hair Care Hair Products Centeno

https://ebookbell.com/product/classic-hairstyles-for-men-an-
illustrated-guide-to-mens-hair-style-hair-care-hair-products-
centeno-11368626

Financing Infrastructure Projects Merna Tony Njiru Cyrus

https://ebookbell.com/product/financing-infrastructure-projects-merna-
tony-njiru-cyrus-5309760

Big Book Of Embroidery 250 Stitches And 29 Creative Projects Rene Mery

https://ebookbell.com/product/big-book-of-embroidery-250-stitches-
and-29-creative-projects-rene-mery-48670340
MERN
Projects for
Beginners
Create Five Social Web Apps Using
MongoDB, Express.js, React, and Node

Nabendu Biswas
MERN Projects for
Beginners
Create Five Social Web Apps
Using MongoDB, Express.js,
React, and Node

Nabendu Biswas
MERN Projects for Beginners: Create Five Social Web Apps Using MongoDB,
Express.js, React, and Node
Nabendu Biswas
Bhopal, India

ISBN-13 (pbk): 978-1-4842-7137-7 ISBN-13 (electronic): 978-1-4842-7138-4


https://doi.org/10.1007/978-1-4842-7138-4

Copyright © 2021 by Nabendu Biswas


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Louise Corrigan
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 NY Plaza, New
York, NY 10014. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit
www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/978-­1-­4842-­7137-­7. For more
detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi

Chapter 1: MERN Deployment Setup������������������������������������������������������������������������� 1


The MERN Stack at a Glance��������������������������������������������������������������������������������������������������������� 1
Firebase Hosting Initial Setup������������������������������������������������������������������������������������������������������� 2
MongoDB Setup���������������������������������������������������������������������������������������������������������������������������� 6
Creating a New Project������������������������������������������������������������������������������������������������������������ 6
Database User and Network Access������������������������������������������������������������������������������������������� 12
Deploying the Back End to Heroku���������������������������������������������������������������������������������������������� 16
Deploying the Front End to Firebase������������������������������������������������������������������������������������������� 23
Install Node.js and npm�������������������������������������������������������������������������������������������������������������� 25
Summary������������������������������������������������������������������������������������������������������������������������������������ 31

Chapter 2: Building a Dating App with MERN��������������������������������������������������������� 33


Firebase Hosting Initial Setup����������������������������������������������������������������������������������������������������� 34
React Basic Setup����������������������������������������������������������������������������������������������������������������������� 34
Creating a Header Component���������������������������������������������������������������������������������������������������� 36
Creating the Dating Cards Component���������������������������������������������������������������������������������������� 39
Creating the Swipe Buttons Component������������������������������������������������������������������������������������� 44
Initial Back-End Setup���������������������������������������������������������������������������������������������������������������� 47
MongoDB Setup�������������������������������������������������������������������������������������������������������������������������� 49
Initial Route Setup����������������������������������������������������������������������������������������������������������������������� 49
Database User and Network Access������������������������������������������������������������������������������������������� 50
MongoDB Schema and Routes���������������������������������������������������������������������������������������������������� 51
Integrating the Back End with the Front End������������������������������������������������������������������������������ 56

iii
Table of Contents

Deploying the Back End to Heroku���������������������������������������������������������������������������������������������� 58


Deploying the Front End to Firebase������������������������������������������������������������������������������������������� 59
Summary������������������������������������������������������������������������������������������������������������������������������������ 59

Chapter 3: Building a Short Video App with MERN������������������������������������������������� 61


Firebase Hosting Initial Setup����������������������������������������������������������������������������������������������������� 62
React Basic Setup����������������������������������������������������������������������������������������������������������������������� 63
Creating a Video Component������������������������������������������������������������������������������������������������������� 63
Creating a Video Footer Component�������������������������������������������������������������������������������������������� 69
Creating a Video Sidebar Component����������������������������������������������������������������������������������������� 75
Making Components Dynamic���������������������������������������������������������������������������������������������������� 78
Initial Back-End Setup���������������������������������������������������������������������������������������������������������������� 81
MongoDB Setup��������������������������������������������������������������������������������������������������������������������� 83
Initial Route Setup����������������������������������������������������������������������������������������������������������������� 83
Database User and Network Access�������������������������������������������������������������������������������������� 84
MongoDB Schema and Routes���������������������������������������������������������������������������������������������� 85
Integrating the Back End with the Front End������������������������������������������������������������������������������ 90
Deploying the Back End to Heroku���������������������������������������������������������������������������������������������� 93
Deploying the Front End to Firebase������������������������������������������������������������������������������������������� 94
Summary������������������������������������������������������������������������������������������������������������������������������������ 94

Chapter 4: Building a Messaging App with MERN�������������������������������������������������� 95


Firebase Hosting Initial Setup����������������������������������������������������������������������������������������������������� 96
React Basic Setup����������������������������������������������������������������������������������������������������������������������� 97
Creating a Sidebar Component��������������������������������������������������������������������������������������������������� 97
Creating a Sidebar Chat Component����������������������������������������������������������������������������������������� 105
Creating a Chat Component������������������������������������������������������������������������������������������������������ 108
Creating a Chat Footer Component������������������������������������������������������������������������������������������� 114
Initial Back-End Setup�������������������������������������������������������������������������������������������������������������� 117
MongoDB Setup������������������������������������������������������������������������������������������������������������������������ 119
Initial Route Setup��������������������������������������������������������������������������������������������������������������������� 119

iv
Table of Contents

Database User and Network Access����������������������������������������������������������������������������������������� 120


MongoDB Schema and Routes�������������������������������������������������������������������������������������������������� 121
Configuring Pusher������������������������������������������������������������������������������������������������������������������� 126
Adding Pusher to the Back End������������������������������������������������������������������������������������������������� 130
Adding Pusher to the Front End������������������������������������������������������������������������������������������������ 133
Integrating the Back End with the Front End���������������������������������������������������������������������������� 135
Additional Setup������������������������������������������������������������������������������������������������������������������������ 141
Creating a Login Component����������������������������������������������������������������������������������������������������� 148
Adding Google Authentication��������������������������������������������������������������������������������������������������� 151
Using Redux and Context API���������������������������������������������������������������������������������������������������� 155
Using Redux Data in Other Components����������������������������������������������������������������������������������� 159
Deploying the Back End to Heroku�������������������������������������������������������������������������������������������� 166
Deploying the Front End to Firebase����������������������������������������������������������������������������������������� 167
Summary���������������������������������������������������������������������������������������������������������������������������������� 168

Chapter 5: Building a Photo-Based Social Network with MERN��������������������������� 169


Firebase Hosting Initial Setup��������������������������������������������������������������������������������������������������� 170
React Basic Setup��������������������������������������������������������������������������������������������������������������������� 172
Creating a Header Component�������������������������������������������������������������������������������������������������� 172
Creating a Post Component������������������������������������������������������������������������������������������������������ 173
Making Components Dynamic�������������������������������������������������������������������������������������������������� 177
Firebase Authentication Setup�������������������������������������������������������������������������������������������������� 180
Creating a Modal for Signup����������������������������������������������������������������������������������������������������� 182
Sign up with Firebase��������������������������������������������������������������������������������������������������������������� 187
Sign in with Firebase���������������������������������������������������������������������������������������������������������������� 189
Adding Posts and Images��������������������������������������������������������������������������������������������������������� 191
Initial Back-End Setup�������������������������������������������������������������������������������������������������������������� 197
MongoDB Setup������������������������������������������������������������������������������������������������������������������������ 199
Initial Route Setup��������������������������������������������������������������������������������������������������������������������� 199
Database User and Network Access����������������������������������������������������������������������������������������� 200

v
Table of Contents

MongoDB Schema and Routes�������������������������������������������������������������������������������������������������� 201


Integrating the Back End with the Front End���������������������������������������������������������������������������� 206
Configuring Pusher������������������������������������������������������������������������������������������������������������������� 213
Adding Pusher to the Back End������������������������������������������������������������������������������������������������� 213
Adding Pusher to the Front End������������������������������������������������������������������������������������������������ 215
Hiding Secrets��������������������������������������������������������������������������������������������������������������������������� 217
Deploying the Back End to Heroku�������������������������������������������������������������������������������������������� 218
Deploying the Front End to Firebase����������������������������������������������������������������������������������������� 219
Summary���������������������������������������������������������������������������������������������������������������������������������� 220

Chapter 6: Build a Popular Social Network with MERN���������������������������������������� 221


Firebase Hosting Initial Setup��������������������������������������������������������������������������������������������������� 222
React Basic Setup��������������������������������������������������������������������������������������������������������������������� 223
Adding a Styled Component������������������������������������������������������������������������������������������������������ 223
Creating a Header Component�������������������������������������������������������������������������������������������������� 224
Creating Sidebar Components�������������������������������������������������������������������������������������������������� 229
Creating a Feed Component������������������������������������������������������������������������������������������������������ 232
Adding a Widget������������������������������������������������������������������������������������������������������������������������ 237
Creating a Messenger Component�������������������������������������������������������������������������������������������� 241
Creating a Post Component������������������������������������������������������������������������������������������������������ 245
Google Authentication Setup����������������������������������������������������������������������������������������������������� 250
Creating a Login Component����������������������������������������������������������������������������������������������������� 251
Using Redux and Context API���������������������������������������������������������������������������������������������������� 255
Using Redux Data in Other Components����������������������������������������������������������������������������������� 258
Initial Back End Setup��������������������������������������������������������������������������������������������������������������� 261
MongoDB Setup������������������������������������������������������������������������������������������������������������������������ 263
Initial Route Setup��������������������������������������������������������������������������������������������������������������������� 263
Database User and Network Access����������������������������������������������������������������������������������������� 264
Storing Images in MongoDB����������������������������������������������������������������������������������������������������� 265
MongoDB Schema and Routes�������������������������������������������������������������������������������������������������� 271

vi
Table of Contents

Integrating the Back End with the Front End���������������������������������������������������������������������������� 272


Configuring Pusher������������������������������������������������������������������������������������������������������������������� 277
Adding Pusher to the Back End������������������������������������������������������������������������������������������������� 277
Adding Pusher to the Front End������������������������������������������������������������������������������������������������ 279
Deploying the Back End to Heroku�������������������������������������������������������������������������������������������� 280
Deploying the Front End to Firebase����������������������������������������������������������������������������������������� 280
Deploying the Front End to Firebase����������������������������������������������������������������������������������������� 281
Summary���������������������������������������������������������������������������������������������������������������������������������� 282

Index��������������������������������������������������������������������������������������������������������������������� 283

vii
About the Author
Nabendu Biswas is a full-stack JavaScript developer who has been working in the IT
industry for the past 16 years. He has worked for some of the world’s top development
firms and investment banks. Nabendu is a tech blogger who publishes on DEV
Community (dev.to), Medium (medium.com), and The Web Dev(TWD) (thewebdev.
tech). He is an all-around nerd who is passionate about everything JavaScript, React, and
Gatsby. You can find him on Twitter @nabendu82.

ix
About the Technical Reviewer
Alexander Nnakwue is a self-taught software engineer with experience in back-end and
full-stack engineering. With experience spanning more than four years, he loves to solve
problems at scale. Currently, he is interested in startups, open source web development,
and distributed systems. In his spare time, Alexander loves watching soccer and listening
to all genres of music.

xi
CHAPTER 1

MERN Deployment Setup


Welcome to MERN Projects for Beginners, where you learn to build awesome web apps
using the MERN (MongoDB, Express, React, Node.js) framework. This stack is in high
demand in the startup sector because you can make a fully functional web app using it.
A front-end engineer who knows HTML, CSS, and React can quickly learn Node.js and
MongoDB and build a fully production-ready web app.
In this book, you learn how to host a back end using Node.js code in Heroku. The
front-end site uses React code and Firebase hosting. It is also hosted through a cloud
database called MongoDB Atlas. Most of the hosting setups are the same in the next five
chapters, so it won’t be repeated in most chapters.

The MERN Stack at a Glance


Before installing Firebase, let’s discuss the basics of the technologies involved in the
MERN stack.

• MongoDB is an open source document based on the NoSQL database.


It is different from traditional relational databases that store data in
tables. It stores data in JSON-like documents. It is highly scalable and
performance-oriented and thus suited for modern-day web apps.

• React is the most popular open source JavaScript library for building
a website’s or web app’s front end or user interface. It is developed
and maintained by Facebook.

• Node.js lets developers write server-side code using JavaScript. It


integrates very well with React or Angular at the front end and with
MongoDB for databases.

• Express is a framework of Node.js, and through it, you can create API
endpoints, which are the basis of any back-end server-side code.

1
© Nabendu Biswas 2021
N. Biswas, MERN Projects for Beginners, https://doi.org/10.1007/978-1-4842-7138-4_1
Chapter 1 MERN Deployment Setup

Firebase Hosting Initial Setup


You need a Google account to work with Firebase. Go to https://firebase.google.com
and click Go to console in the top-right corner. You must be logged in to your Google
account to do so, as seen in Figure 1-1.

Figure 1-1. Firebase console caption

2
Chapter 1 MERN Deployment Setup

Click the Add project link on the page, as seen in Figure 1-2.

Figure 1-2. Add project

3
Chapter 1 MERN Deployment Setup

On this page, name the project dating-app-mern, and then click the Continue
button, as seen in Figure 1-3. Note that this is just an installation instruction. You start
building the app in the next chapter.

Figure 1-3. App name

On the next page, click the Create project button, as seen in Figure 1-4.

4
Chapter 1 MERN Deployment Setup

Figure 1-4. Create project

It takes some time to create the project, as seen in Figure 1-5.

Figure 1-5. Project created

5
Chapter 1 MERN Deployment Setup

M
 ongoDB Setup
MongoDB is the database that you work with on the cloud. It is also known as
MongoDB Atlas. This is easier to work with than setting up on a local machine. Go to
www.mongodb.com and log in or create a new account.

Creating a New Project


After logging in, you see a screen similar to the one shown in Figure 1-6. Click the New
Project button.

Figure 1-6. MongoDB new project

6
Chapter 1 MERN Deployment Setup

Name your project dating-app-mern, and then click the Next button, as seen in
Figure 1-7.

Figure 1-7. Project name

On the next screen, click the Create Project button, as seen in Figure 1-8.

Figure 1-8. MongoDB Create Project


7
Chapter 1 MERN Deployment Setup

On the next screen, click the Build a Cluster button, as seen in Figure 1-9.

Figure 1-9. Build a Cluster

On the next screen, select the Free tier, as seen in Figure 1-10.

8
Chapter 1 MERN Deployment Setup

Figure 1-10. Free tier

On the next screen, you need to choose the AWS region in which to create the
database. (I chose Mumbai because I live in India, and this gives me low latency.)
Afterward, click the Create Cluster button, as seen in Figure 1-11.

9
Chapter 1 MERN Deployment Setup

Figure 1-11. Choose region

The next screen shows that the cluster has been created, which takes time. You can
go back and create your first API endpoint, as seen in Figure 1-12.

10
Chapter 1 MERN Deployment Setup

Figure 1-12. Cluster created

11
Chapter 1 MERN Deployment Setup

Database User and Network Access


To create a user in MongoDB, click the Database Access tab and then the Add New
Database User button, as seen in Figure 1-13.

Figure 1-13. Create database user

On the next screen, you need to enter a username and a password, as seen in
Figure 1-14. You must remember both. Next, scroll down and click the Add User button.

12
Chapter 1 MERN Deployment Setup

Figure 1-14. Add user

Next, go to the Network Access tab and click the Add IP Address button, as seen in
Figure 1-15.

13
Chapter 1 MERN Deployment Setup

Figure 1-15. Network access

In the popup window, click the ALLOW ACCESS FROM ANYWHERE button and
then click the Confirm button, as seen in Figure 1-16.

Figure 1-16. Allow access


14
Chapter 1 MERN Deployment Setup

Next, return to the Cluster tab and click the CONNECT button, which opens the
popup window shown in Figure 1-17. Click the Connect your application tab.

Figure 1-17. Connect your application

15
Chapter 1 MERN Deployment Setup

Copy the connection URL by clicking the Copy button, as seen in Figure 1-18.

Figure 1-18. Connection string

Deploying the Back End to Heroku


Once you complete the back-end code, go to www.heroku.com to deploy the back end.
Log in to your Heroku account, click the New drop-down menu, and then click the
Create new app button, as seen in Figure 1-19. You can also do this from the command
line using the Heroku CLI, but that is not covered here.

16
Chapter 1 MERN Deployment Setup

Figure 1-19. Heroku login

17
Chapter 1 MERN Deployment Setup

Next, name the app and click the Create app button, as seen in Figure 1-20.

Figure 1-20. Heroku app name

The next screen shows all the commands to deploy your app, but you need the
Heroku CLI. Click the link and follow the instructions to install it on your operating
system, as seen in Figure 1-21.

18
Chapter 1 MERN Deployment Setup

Figure 1-21. Heroku instructions

Run the heroku login command in the backend folder. You are asked for permission
to open the browser. This command asks you to press any key to open in the browser.

19
Chapter 1 MERN Deployment Setup

Figure 1-22.

Here, you can log in with your credentials, as seen in Figure 1-23.

20
Chapter 1 MERN Deployment Setup

Figure 1-23. Login credentials

After successfully logging in, you see the page shown in Figure 1-24, which you need
to close.

21
Chapter 1 MERN Deployment Setup

Figure 1-24. Close popup

You need to push the code from your local machine to the Heroku repository. Now
that you are logged in to your account, you can run the following command to connect to
Heroku Git.

heroku git:remote -a dating-mern-backend

Next, let’s run the familiar git command to commit the code. Now, Git is software
that tracks changes in a file; it is a must in software development. The following
commands add code to the staging area, then commits it. The push command pushes it
to remote Heroku servers.

git add .
git commit -m "backend code complete"
git push heroku master

22
Chapter 1 MERN Deployment Setup

After the installation is done, click the Open app button, which takes you to the
deploy site, as seen in Figure 1-25.

Figure 1-25. Open back-end app

Deploying the Front End to Firebase


After the front-end project is complete (in an upcoming chapter), you can deploy it
in Firebase. Go to the frontend folder and run the firebase login command in the
terminal. If you are running it for the first time, a popup window opens. Next, run the
firebase init command. Type Y to proceed.

firebase login
firebase init

Use the down arrow key to go to Hosting, as seen in Figure 1-26. Press the spacebar
to select it, and then press the Enter key.

23
Chapter 1 MERN Deployment Setup

Figure 1-26. Configure

Select Use an existing project, as seen in Figure 1-27, and press the Enter key.

Figure 1-27. Existing project

Next, select the correct project, which is dating-app-mern-453b1 in my case, as


seen in Figure 1-28.

Figure 1-28. Correct project

Next, choose the public directory, which is build. The following question asks about
a single-page app; answer Yes. The next question is about GitHub deploys; answer No, as
seen in Figure 1-29.

24
Chapter 1 MERN Deployment Setup

Figure 1-29. Build

Next, run npm run build in the frontend folder for an optimal production build. The
final command, firebase deploy, deploys the project to Firebase. If successful, the site
is now live, which is shown in upcoming chapters.

Install Node.js and npm


Let’s go over installing Node.js and npm (node package manager) if they are not already
installed on your system. Most of the code in this book requires Node.js and npm. The
React front-end code also requires Node.js. Through npm, you can install many small
open sourced programs, which adds functionality to both React and Node.js.
When you install Node.js, npm is also automatically installed on your system. The
following instructions are for a Windows-based system, although macOS users can find a
similar guide on the Internet.
In your web browser, enter https://nodejs.org/en/download/ and click Windows
Installer, as seen in Figure 1-30. Again, it also installs npm.

25
Chapter 1 MERN Deployment Setup

Figure 1-30. Node.js installer

The downloaded file is installed in your Download folder by default. Click it, and
then click the Run button, as seen in Figure 1-31.

26
Chapter 1 MERN Deployment Setup

Figure 1-31. Run button

In the Node.js installation popup window, click the Next button, as seen in Figure 1-­32.

Figure 1-32. Node.js welcome

27
Chapter 1 MERN Deployment Setup

Click to accept the end-user license agreement, and then click the Next button, as
seen in Figure 1-33.

Figure 1-33. Agreement

Next, I advise that you use the installation location shown in Figure 1-34.

28
Chapter 1 MERN Deployment Setup

Figure 1-34. Installation location


The wizard asks you to choose a package. Keep the defaults, as seen in Figure 1-35.

Figure 1-35. Default packages


29
Chapter 1 MERN Deployment Setup

Next, click the check box and then the Next button, as seen in Figure 1-36.

Figure 1-36. Dependencies

Then, click the Install button, as seen in Figure 1-37.

30
Chapter 1 MERN Deployment Setup

Figure 1-37. Install

Once the installation is done, run the following commands to check the versions and
verify that everything is right.

node –v
npm -v

Summary
In this chapter, we have learnt about all the different technologies to create a
MERN(MongoDB, Express, ReactJS, NodeJS) project. We have also learnt how to deploy
them in different environments and we will be using them in the next chapters.

31
CHAPTER 2

Building a Dating App


with MERN
Welcome to Chapter 2, where you build a dating app using the MERN (MongoDB,
Express, React, Node.js) framework. The back end is hosted in Heroku, and the front-end
site uses Firebase hosting. The icons in the project come from Material-UI.
The web app has simple functionality and is the first MERN stack project. A
screenshot of the finished app, which is deployed in Firebase, is shown in Figure 2-1.
All the data comes from a MongoDB database, with API endpoints set in Node.js.

Figure 2-1. Finished app


33
© Nabendu Biswas 2021
N. Biswas, MERN Projects for Beginners, https://doi.org/10.1007/978-1-4842-7138-4_2
Chapter 2 Building a Dating App with MERN

Let’s review the React front end and then move to the back end. Open your terminal
and create a dating-app-mern folder. Inside it, use create-react-app to create a new app
called dating-app-frontend. The following are the commands to do this.

mkdir dating-app-mern
cd dating-app-mern
npx create-react-app dating-app-frontend

Firebase Hosting Initial Setup


Since the front-end site is hosted through Firebase, let’s create the basic setting while
create-react-app creates the React app. Following the same setup instructions in
Chapter 1, I created dating-app-mern in the Firebase console.

React Basic Setup


Return to the React project and cd to the dating-app-frontend directory. Start the React
app with npm start.

cd dating-app-frontend
npm start

Next, let’s delete some of the files that you don’t need. Figure 2-2 shows how the app
looks on localhost.

34
Chapter 2 Building a Dating App with MERN

Figure 2-2. Delete files


Let’s remove all the unnecessary boilerplate code. The index.js file should look like
the following.

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
35
Chapter 2 Building a Dating App with MERN

App.js contains only the text Dating App MERN. All the content from the App.css
file has been removed.

import './App.css';

function App() {
  return (
    <div className="app">
      <h1>Dating App MERN </h1>
    </div>
  );
}

export default App;

In index.css, update the CSS to have margin: 0 at the top.

* {
       margin: 0;
  }

Figure 2-3 shows how the app looks on localhost.

Figure 2-3. Initial app

Creating a Header Component


Let’s create a header component. First, you must install Material-UI (https://material-
ui.com), which provides the icons. You need to do two npm installs, as per the Material-
UI documentation. Install the core through the integrated terminal in the dating-app-
frontend folder.

npm i @material-ui/core @material-ui/icons

36
Chapter 2 Building a Dating App with MERN

Next, create a components folder inside the src folder. Create two files—Header.js
and Header.css—inside the components folder. Header.js has three things: a person
icon, a logo, and a forum icon. The logo is taken from the project’s public directory,
which contains the React logo by default.
The following is the Header.js file’s content.

import React from 'react'


import './Header.css'
import PersonIcon from '@material-ui/icons/Person'
import IconButton from '@material-ui/core/IconButton'
import ForumIcon from '@material-ui/icons/Forum'

const Header = () => {


    return (
        <div className="header">
            <IconButton>
                <PersonIcon fontSize="large" className="header__icon" />
            </IconButton>
            <img className="header__logo" src="logo192.png" alt="header" />
            <IconButton>
                <ForumIcon fontSize="large" className="header__icon" />
            </IconButton>
        </div>
    )
}

export default Header

Include the Header component in the App.js file and on localhost. The updated
code is marked in bold.

import './App.css';
import Header from './components/Header';

function App() {
  return (

37
Chapter 2 Building a Dating App with MERN

    <div className="app">
      <Header  />
    </div>
  );
}

export default App;

The Header.css file contains the following content, including simple styles, which
completes the header.

.header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 100;
    border-bottom: 1px solid #f9f9f9;
}

.header__logo{
    object-fit: contain;
    height: 40px;
}

.header__icon{
    padding: 20px;
}

Figure 2-4 shows how the app looks now on localhost.

Figure 2-4. Header component

38
Chapter 2 Building a Dating App with MERN

Creating the Dating Cards Component


Let’s now work on the second component. Create two files—DatingCards.js and
DatingCards.css—inside the components folder. Then include the DatingCards
component in the App.js file. The updated code is marked in bold.

import './App.css';
import Header from './components/Header';
import DatingCards from './components/DatingCards';

function App() {
  return (
    <div className="app">
      <Header  />
     < DatingCards />
    </div>
  );
}

export default App;

Before moving forward, you need to install a react-tinder-card package. This


package has a feature that provides the swipe effect.

npm i react-tinder-card

Next, put the content in DatingCards.js. Here, inside a people state variable, you store
the name and images of four people. Next, import DatingCard and use it as a component.
Here, you use the props mentioned in the react-tinder-card documentation.
The swiped and outOfFrame functions are required. When looping through each
person, use the imgUrl background image and display the name in the h3 tag.

import React, { useState } from 'react'


import DatingCard from 'react-tinder-card'
import './DatingCards.css'

const DatingCards = () => {


    const [people, setPeople] = useState([

39
Chapter 2 Building a Dating App with MERN

       { name: "Random Guy", imgUrl: "https://images.unsplash.com/photo-


1520409364224-63400afe26e5?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVu
fDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=658&q=80" },

       { name: "Another Guy", imgUrl: "https://images.unsplash.com/photo-


1519085360753-af0119f7cbe7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90b
y1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=634&q=80" },

       { name: "Random Girl", imgUrl: "https://images.unsplash.com/photo-


1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90b
y1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=634&q=80" },

       { name: "Another Girl", imgUrl: "https://images.unsplash.com/photo-


1529626455594-4ff0802cfb7e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVu
fDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80" }
])
    const swiped = (direction, nameToDelete) => {
        console.log("receiving " + nameToDelete)
    }
    const outOfFrame = (name) => {
        console.log(name + " left the screen!!")
    }
    return (
        <div className="datingCards">
            <div className="datingCards__container">
                {people.map((person) => (
                    <DatingCard
                        className="swipe"
                        key={person.name}
                        preventSwipe={['up', 'down']}
                        onSwipe={(dir) => swiped(dir, person.name)}
                        onCardLeftScreen={() => outOfFrame(person.name)} >
                        <div style={{ backgroundImage: `url(${person.
imgUrl})`}} className="card">
                            <h3>{person.name}</h3>

40
Chapter 2 Building a Dating App with MERN

                        </div>
                    </DatingCard>
                ))}
            </div>
        </div>
    )
}

export default DatingCards

Localhost shows four “people,” as seen in Figure 2-5, but you need to style
everything.

Figure 2-5. All people

Add the first styles in the DatingCards.css file, and make datingCards__container
a flexbox. Next, style each card to contain the image and other things. Note that you are
setting position: relative for each card, which offsets the element relative to itself and
provides width and height.

.datingCards__container{
    display: flex;
    justify-content: center;
    margin-top: 10vh;
}

.card{
    position: relative;
    background-color: white;
    width: 600px;
    padding: 20px;

41
Discovering Diverse Content Through
Random Scribd Documents
legislative and judicial proceedings. 5. It tends to impair the
property of the citizens, and, in some instances, that of the
States, by destroying the State banks in which they have
invested their money. 6. It is injurious to the commerce of the
States (I speak of the Western States), by substituting a trade
in bills of exchange, for a trade in the products of the country. 7.
It fastens a vampire on the bosom of the State, to suck away its
gold and silver, and to co-operate with the course of trade, of
federal legislation, and of exchange, in draining the South and
West of all their hard money. The Southern States, with their
thirty millions of annual exports in cotton, rice, and tobacco, and
the Western States, with their twelve millions of provisions and
tobacco exported from New Orleans, and five millions consumed
in the South, and on the lower Mississippi,—that is to say, with
three fifths of the marketable productions of the Union, are not
able to sustain thirty specie paying banks; while the minority of
the States north of the Potomac, without any of the great
staples for export, have above four hundred of such banks.
These States, without rice, without cotton, without tobacco,
without sugar, and with less flour and provisions, to export, are
saturated with gold and silver; while the Southern and Western
States, with all the real sources of wealth, are in a state of the
utmost destitution. For this calamitous reversal of the natural
order of things, the Bank of the United States stands forth pre-
eminently culpable. Yes, it is pre-eminently culpable! and a
statement in the 'National Intelligencer' of this morning (a paper
which would overstate no fact to the prejudice of the bank),
cites and proclaims the fact which proves this culpability. It
dwells, and exults, on the quantity of gold and silver in the
vaults of the United States Bank. It declares that institution to
be 'overburdened' with gold and silver; and well may it be so
overburdened, since it has lifted the load entirely from the
South and West. It calls these metals 'a drug' in the hands of
the bank; that is to say, an article for which no purchaser can be
found. Let this 'drug,' like the treasures of the dethroned Dey of
Algiers, be released from the dominion of its keeper; let a part
go back to the South and West, and the bank will no longer
complain of repletion, nor they of depletion.
"8. Exemption of the stockholders from individual liability on
the failure of the bank. This privilege derogates from the
common law, is contrary to the principle of partnerships, and
injurious to the rights of the community. It is a peculiar privilege
granted by law to these corporators, and exempting them from
liability, except in their corporate capacity, and to the amount of
the assets of the corporation. Unhappily these assets are never
assez, that is to say, enough, when occasion comes for recurring
to them. When a bank fails, its assets are always less than its
debts; so that responsibility fails the instant that liability
accrues. Let no one say that the bank of the United States is too
great to fail. One greater than it, and its prototype, has failed,
and that in our own day, and for twenty years at a time: the
Bank of England failed in 1797, and the Bank of the United
States was on the point of failing in 1819. The same cause,
namely, stockjobbing and overtrading, carried both to the brink
of destruction; the same means saved both, namely, the name,
the credit, and the helping hand of the governments which
protected them. Yes, the Bank of the United States may fail;
and its stockholders live in splendor upon the princely estates
acquired with its notes, while the industrious classes, who hold
these notes, will be unable to receive a shilling for them. This is
unjust. It is a vice in the charter. The true principle in banking
requires each stockholder to be liable to the amount of his
shares; and subjects him to the summary action of every holder
on the failure of the institution, till he has paid up the amount of
his subscription. This is the true principle. It has prevailed in
Scotland for the last century, and no such thing as a broken
bank has been known there in all that time.
"9. To have the United States for a partner. Sir, there is one
consequence, one result of all partnerships between a
government and individuals, which should of itself, and in a
mere mercantile point of view, condemn this association on the
part of the federal government. It is the principle which puts the
strong partner forward to bear the burden whenever the
concern is in danger. The weaker members flock to the strong
partner at the approach of the storm, and the necessity of
venturing more to save what he has already staked, leaves him
no alternative. He becomes the Atlas of the firm, and bears all
upon his own shoulders. This is the principle: what is the fact?
Why, that the United States has already been compelled to
sustain the federal bank; to prop it with her revenues and its
credit in the trials and crisis of its early administration. I pass
over other instances of the damage suffered by the United
States on account of this partnership; the immense standing
deposits for which we receive no compensation; the loan of five
millions of our own money, for which we have paid a million and
a half in interest; the five per cent. stock note, on which we
have paid our partners four million seven hundred and twenty-
five thousand dollars in interest; the loss of ten millions on the
three per cent. stock, and the ridiculous catastrophe of the
miserable bonus, which has been paid to us with a fraction of
our own money: I pass over all this, and come to the point of a
direct loss, as a partner, in the dividends upon the stock itself.
Upon this naked point of profit and loss, to be decided by a rule
in arithmetic, we have sustained a direct and heavy loss. The
stock held by the United States, as every body knows, was
subscribed, not paid. It was a stock note, deposited for seven
millions of dollars, bearing an interest of five per cent. The
inducement to this subscription was the seductive conception
that, by paying five per cent. on its note, the United States
would clear four or five per cent. in getting a dividend of eight
or ten. This was the inducement; now for the realization of this
fine conception. Let us see it. Here it is; an official return, from
the Register of the Treasury of interest paid, and of dividends
received. The account stands thus:
Interest paid by the United States, $4,725,000
Dividends received by the United States, 4,629,426
Loss to the United States, $95,574
"Disadvantageous as this partnership must be to the United
States in a moneyed point of view, there is a far more grave and
serious aspect under which to view it. It is the political aspect,
resulting from the union between the bank and the government.
This union has been tried in England, and has been found there
to be just as disastrous a conjunction as the union between
church and state. It is the conjunction of the lender and the
borrower, and Holy Writ has told us which of these categories
will be master of the other. But suppose they agree to drop
rivalry, and unite their resources. Suppose they combine, and
make a push for political power: how great is the mischief which
they may not accomplish! But, on this head, I wish to use the
language of one of the brightest patriots of Great Britain; one
who has shown himself, in these modern days, to be the worthy
successor of those old iron barons whose patriotism
commanded the unpurchasable eulogium of the elder Pitt. I
speak of Sir William Pulteney, and his speech against the Bank
of England, in 1797.
"THE SPEECH:—EXTRACT.
"'I have said enough to show that government has been
rendered dependent on the bank, and more particularly so in
the time of war; and though the bank has not yet fallen into the
hands of ambitious men, yet it is evident that it might, in such
hands, assume a power sufficient to control and overawe, not
only the ministers, but king, lords, and commons. * * * * * * As
the bank has thus become dangerous to government, it might,
on the other hand, by uniting with an ambitious minister,
become the means of establishing a fourth estate, sufficient to
involve this nation in irretrievable slavery, and ought, therefore,
to be dreaded as much as a certain East India bill was justly
dreaded, at a period not very remote. I will not say that the
present minister (the younger Pitt), by endeavoring, at this
crisis, to take the Bank of England under his protection, can
have any view to make use, hereafter, of that engine to
perpetuate his own power, and to enable him to domineer over
our constitution: if that could be supposed, it would only show
that men can entertain a very different train of ideas, when
endeavoring to overset a rival, from what occurs to them when
intending to support and fix themselves. My object is to secure
the country against all risk either from the bank as opposed to
government, or as the engine of ambitious men.'
"And this is my object also. I wish to secure the Union from
all chance of harm from this bank. I wish to provide against its
friendship, as well as its enmity—against all danger from its
hug, as well as from its blow. I wish to provide against all risk,
and every hazard; for, if this risk and hazard were too great to
be encountered by King, Lords, and Commons, in Great Britain,
they must certainly be too great to be encountered by the
people of the United States, who are but commons alone.
"10. To have foreigners for partners. This, Mr. President, will
be a strange story to be told in the West. The downright and
upright people of that unsophisticated region believe that words
mean what they signify, and that 'the Bank of the United States'
is the Bank of the United States. How great then must be their
astonishment to learn that this belief is a false conception, and
that this bank (its whole name to the contrary notwithstanding)
is just as much the bank of foreigners as it is of the federal
government. Here I would like to have the proof—a list of the
names and nations, to establish this almost incredible fact. But I
have no access except to public documents, and from one of
these I learn as much as will answer the present pinch. It is the
report of the Committee of Ways and Means, in the House of
Representatives, for the last session of Congress. That report
admits that foreigners own seven millions of the stock of this
bank; and every body knows that the federal government owns
seven millions also.
"Thus it is proved that foreigners are as deeply interested in
this bank as the United States itself. In the event of a renewal of
the charter they will be much more deeply interested than at
present; for a prospect of a rise in the stock to two hundred and
fifty, and the unsettled state of things in Europe, will induce
them to make great investments. It is to no purpose to say that
the foreign stockholders cannot be voters or directors. The
answer to that suggestion is this: the foreigners have the
money; they pay down the cash, and want no accommodations;
they are lenders, not borrowers; and in a great moneyed
institution, such stockholders must have the greatest influence.
The name of this bank is a deception upon the public. It is not
the bank of the federal government, as its name would import,
nor of the States which compose this Union; but chiefly of
private individuals, foreigners as well as natives, denizens, and
naturalized subjects. They own twenty-eight millions of the
stock, the federal government but seven millions, and these
seven are precisely balanced by the stock of the aliens. The
federal government and the aliens are equal, owning one fifth
each; and there would be as much truth in calling it the English
Bank as the Bank of the United States. Now mark a few of the
privileges which this charter gives to these foreigners. To be
landholders, in defiance of the State laws, which forbid aliens to
hold land; to be landlords by incorporation, and to hold
American citizens for tenants; to hold lands in mortmain; to be
pawnbrokers and merchants by incorporation; to pay the
revenue of the United States in their own notes; in short, to do
every thing which I have endeavored to point out in the long
and hideous list of exclusive privileges granted to this bank. If I
have shown it to be dangerous for the United States to be in
partnership with its own citizens, how much stronger is not the
argument against a partnership with foreigners? What a
prospect for loans when at war with a foreign power, and the
subjects of that power large owners of the bank here, from
which alone, or from banks liable to be destroyed by it, we can
obtain money to carry on the war! What a state of things, if, in
the division of political parties, one of these parties and the
foreigners, coalescing, should have the exclusive control of all
the money in the Union, and, in addition to the money, should
have bodies of debtors, tenants, and bank officers stationed in
all the States, with a supreme and irresponsible system of
centralism to direct the whole! Dangers from such contingencies
are too great and obvious to be insisted upon. They strike the
common sense of all mankind, and were powerful
considerations with the old whig republicans for the non-
renewal of the charter of 1791. Mr. Jefferson and the whig
republicans staked their political existence on the non-renewal
of that charter. They succeeded; and, by succeeding, prevented
the country from being laid at the mercy of British and ultra-
federalists for funds to carry on the last war. It is said the United
States lost forty millions by using depreciated currency during
the last war. That, probably, is a mistake of one half. But be it
so! For what are forty millions compared to the loss of the war
itself—compared to the ruin and infamy of having the
government arrested for want of money—stopped and paralyzed
by the reception of such a note as the younger Pitt received
from the Bank of England in 1795?
"11. Exemption from due course of law for violations of its
charter.—This is a privilege which affects the administration of
justice, and stands without example in the annals of republican
legislation. In the case of all other delinquents, whether persons
or corporations, the laws take their course against those who
offend them. It is the right of every citizen to set the laws in
motion against every offender; and it is the constitution of the
law, when set in motion, to work through, like a machine,
regardless of powers and principalities, and cutting down the
guilty which may stand in its way. Not so in the case of this
bank. In its behalf, there are barriers erected between the
citizen and his oppressor, between the wrong and the remedy,
between the law and the offender. Instead of a right to sue out
a scire facias or a quo warranto, the injured citizen, with an
humble petition in his hand, must repair to the President of the
United States, or to Congress, and crave their leave to do so. If
leave is denied (and denied it will be whenever the bank has a
peculiar friend in the President, or a majority of such friends in
Congress, the convenient pretext being always at hand that the
general welfare requires the bank to be sustained), he can
proceed no further. The machinery of the law cannot be set in
motion, and the great offender laughs from behind his barrier at
the impotent resentment of its helpless victim. Thus the bank,
for the plainest violations of its charter, and the greatest
oppressions of the citizen, may escape the pursuit of justice.
Thus the administration of justice is subject to be strangled in
its birth for the shelter and protection of this bank. But this is
not all. Another and most alarming mischief results from the
same extraordinary privilege. It gives the bank a direct interest
in the presidential and congressional elections: it gives it need
for friends in Congress and in the presidential chair. Its fate, its
very existence, may often depend upon the friendship of the
President and Congress; and, in such cases, it is not in human
nature to avoid using the immense means in the hands of the
bank to influence the elections of these officers. Take the
existing fact—the case to which I alluded at the commencement
of this speech. There is a case made out, ripe with judicial
evidence, and big with the fate of the bank. It is a case of usury
at the rate of forty-six per cent., in violation of the charter,
which only admits an interest of six. The facts were admitted, in
the court below, by the bank's demurrer; the law was decided,
in the court above, by the supreme judges. The admission
concludes the facts; the decision concludes the law. The
forfeiture of the charter is established; the forfeiture is incurred;
the application of the forfeiture alone is wanting to put an end
to the institution. An impartial President or Congress might let
the laws take their course; those of a different temper might
interpose their veto. What a crisis for the bank! It beholds the
sword of Damocles suspended over its head! What an interest in
keeping those away who might suffer the hair to be cut!
"12. To have all these unjust privileges secured to the
corporators as a monopoly, by a pledge of the public faith to
charter no other bank.—This is the most hideous feature in the
whole mass of deformity. If these banks are beneficial
institutions, why not several? one, at least, and each
independent of the other, to each great section of the Union? If
malignant, why create one? The restriction constitutes the
monopoly, and renders more invidious what was sufficiently
hateful in itself. It is, indeed, a double monopoly, legislative as
well as banking; for the Congress of 1816 monopolized the
power to grant these monopolies. It has tied up the hands of its
successors; and if this can be done on one subject, and for
twenty years, why not upon all subjects, and for all time? Here
is the form of words which operate this double engrossment of
our rights: 'No other bank shall be established by any future law
of Congress, during the continuance of the corporation hereby
enacted, for which the faith of Congress is hereby pledged;'
with a proviso for the District of Columbia. And that no incident
might be wanting to complete the title of this charter, to the
utter reprobation of whig republicans, this compound monopoly,
and the very form of words in which it is conceived, is copied
from the charter of the Bank of England!—not the charter of
William and Mary, as granted in 1694 (for the Bill of Rights was
then fresh in the memories of Englishmen), but the charter as
amended, and that for money, in the memorable reign of Queen
Anne, when a tory queen, a tory ministry, and a tory parliament,
and the apostle of toryism, in the person of Dr. Sacheverell, with
his sermons of divine right, passive obedience, and non-
resistance, were riding and ruling over the prostrate liberties of
England! This is the precious period, and these the noble
authors, from which the idea was borrowed, and the very form
of words copied, which now figure in the charter of the Bank of
the United States, constituting that double monopoly, which
restricts at once the powers of Congress and the rights of the
citizens.
"These, Mr. President, are the chief of the exclusive privileges
which constitute the monopoly of the Bank of the United States.
I have spoken of them, not as they deserved, but as my abilities
have permitted. I have shown you that they are not only evil in
themselves, but copied from an evil example. I now wish to
show you that the government from which we have made this
copy has condemned the original; and, after showing this fact, I
think I shall be able to appeal, with sensible effect, to all liberal
minds, to follow the enlightened example of Great Britain, in
getting rid of a dangerous and invidious institution, after having
followed her pernicious example in assuming it. For this
purpose, I will have recourse to proof, and will read from British
state papers of 1826. I will read extracts from the
correspondence between Earl Liverpool, first Lord of the
Treasury, and Mr. Robinson, Chancellor of the Exchequer, on the
one side, and the Governor and Deputy Governor of the Bank of
England on the other; the subject being the renewal, or rather
non-renewal, of the charter of the Bank of England.

Communications from the First Lord of the Treasury and


Chancellor of the Exchequer to the Governor and Deputy Governor
of the Bank of England.—Extracts.

"'The failures which have occurred in England,


unaccompanied as they have been by the same occurrences in
Scotland, tend to prove that there must have been an unsolid
and delusive system of banking in one part of Great Britain, and
a solid and substantial one in the other. * * * * In Scotland,
there are not more than thirty banks (three chartered), and
these banks have stood firm amidst all the convulsions of the
money market in England, and amidst all the distresses to which
the manufacturing and agricultural interests in Scotland, as well
as in England, have occasionally been subject. Banks of this
description must necessarily be conducted upon the generally
understood and approved principles of banking. * * * * The
Bank of England may, perhaps, propose, as they did upon a
former occasion, the extension of the term of their exclusive
privilege, as to the metropolis and its neighborhood, beyond the
year 1833, as the price of this concession [immediate surrender
of exclusive privileges]. It would be very much to be regretted
that they should require any such condition. * * * * It is
obvious, from what passed before, that Parliament will never
agree to it. * * * * Such privileges are out of fashion; and what
expectation can the bank, under present circumstances,
entertain that theirs will be renewed?'—Jan. 13.

Answer of the Court of Directors.—Extract.

"'Under the uncertainty in which the Court of Directors find


themselves with respect to the death of the bank, and the effect
which they may have on the interests of the bank, this court
cannot feel themselves justified in recommending to the
proprietors to give up the privilege which they now enjoy,
sanctioned and confirmed as it is by the solemn acts of the
legislature.'—Jan. 20.

Second communication from the Ministers.—Extract.

"'The First Lord of the Treasury and Chancellor of the


Exchequer have considered the answer of the bank of the 20th
instant. They cannot but regret that the Court of Directors
should have declined to recommend to the Court of Proprietors
the consideration of the paper delivered by the First Lord of the
Treasury and the Chancellor of the Exchequer to the Governor
and Deputy Governor on the 13th instant. The statement
contained in that paper appears to the First Lord of the Treasury
and the Chancellor of the Exchequer so full and explicit on all
the points to which it related, that they have nothing further to
add, although they would have been, and still are, ready to
answer, as far as possible, any specific questions which might
be put, for the purpose of removing the uncertainty in which the
court of directors state themselves to be with respect to the
details of the plan suggested in that paper.'—Jan. 23.
Second answer of the Bank.—Extract.
"'The Committee of Treasury [bank] having taken into
consideration the paper received from the First Lord of the
Treasury and the Chancellor of the Exchequer, dated January
23d, and finding that His Majesty's ministers persevere in their
desire to propose to restrict immediately the exclusive privilege
of the bank, as to the number of partners engaged in banking
to a certain distance from the metropolis, and also continue to
be of opinion that Parliament would not consent to renew the
privilege at the expiration of the period of their present charter;
finding, also, that the proposal by the bank of establishing
branch banks is deemed by His Majesty's ministers inadequate
to the wants of the country, are of opinion that it would be
desirable for this corporation to propose, as a basis, the act of
6th of George the Fourth, which states, the conditions on which
the Bank of Ireland relinquished its exclusive privileges; this
corporation waiving the question of a prolongation of time,
although the committee [of the bank] cannot agree in the
opinion of the First Lord of the Treasury and the Chancellor of
the Exchequer, that they are not making a considerable
sacrifice, adverting especially to the Bank of Ireland remaining
in possession of that privilege five years longer than the Bank of
England.'—January 25.

"Here, Mr. President, is the end of all the exclusive privileges


and odious monopoly of the Bank of England. That ancient and
powerful institution, so long the haughty tyrant of the moneyed
world—so long the subsidizer of kings and ministers—so long
the fruitful mother of national debt and useless wars—so long
the prolific manufactory of nabobs and paupers—so long the
dread dictator of its own terms to parliament—now droops the
conquered wing, lowers its proud crest, and quails under the
blows if its late despised assailants. It first puts on a courageous
air, and takes a stand upon privileges sanctioned by time, and
confirmed by solemn acts. Seeing that the ministers could have
no more to say to men who would talk of privileges in the
nineteenth century, and being reminded that parliament was
inexorable, the bully suddenly degenerates into the craven, and,
from showing fight, calls for quarter. The directors condescend
to beg for the smallest remnant of their former power, for five
years only; for the city of London even; and offer to send
branches into all quarters. Denied at every point, the subdued
tyrant acquiesces in his fate; announces his submission to the
spirit and intelligence of the age; and quietly sinks down into
the humble, but safe and useful condition of a Scottish
provincial bank.
"And here it is profitable to pause; to look back, and see by
what means this ancient and powerful institution—this Babylon
of the banking world—was so suddenly and so totally
prostrated. Who did it? And with what weapons? Sir, it was done
by that power which is now regulating the affairs of the civilized
world. It was done by the power of public opinion, invoked by
the working members of the British parliament. It was done by
Sir Henry Parnell, who led the attack upon the Wellington
ministry, on the night of the 15th of November; by Sir William
Pulteney, Mr. Grenfell, Mr. Hume, Mr. Edward Ellice, and others,
the working members of the House of Commons, such as had, a
few years before, overthrown the gigantic oppressions of the
salt tax. These are the men who have overthrown the Bank of
England. They began the attack in 1824, under the discouraging
cry of too soon, too soon—for the charter had then nine years
to run! and ended with showing that they had began just soon
enough. They began with the ministers in their front, on the
side of the bank, and ended with having them on their own
side, and making them co-operators in the attack, and the
instruments and inflicters of the fatal and final blow. But let us
do justice to these ministers. Though wrong in the beginning,
they were right in the end; though monarchists, they behaved
like republicans. They were not Polignacs. They yielded to the
intelligence of the age; they yielded to the spirit which
proscribes monopolies and privileges, and in their
correspondence with the bank directors, spoke truth and reason
and asserted liberal principles, with a point and power which
quickly put an end to dangerous and obsolete pretensions. They
told the bank the mortifying truths, that its system was unsolid
and delusive—that its privileges and monopoly were out of
fashion—that they could not be prolonged for five years even—
nor suffered to exist in London alone; and, what was still more
cutting, that the banks of Scotland, which had no monopoly, no
privilege, no connection with the government, which paid
interest on deposits, and whose stockholders were responsible
to the amount of their shares—were the solid and substantial
banks, which alone the public interest could hereafter recognize.
They did their business, when they undertook it, like true men;
and, in the single phrase, 'out of fashion,' achieved the most
powerful combination of solid argument and contemptuous
sarcasm, that ever was compressed into three words. It is a
phrase of electrical power over the senses and passions. It
throws back the mind to the reigns of the Tudors and Stuarts—
the termagant Elizabeth and the pedagogue James—and rouses
within us all the shame and rage we have been accustomed to
feel at the view of the scandalous sales of privileges and
monopolies which were the disgrace and oppression of these
wretched times. Out of fashion! Yes; even in England, the land
of their early birth, and late protection. And shall they remain in
fashion here? Shall republicanism continue to wear, in America,
the antique costume which the doughty champions of
antiquated fashion have been compelled to doff in England?
Shall English lords and ladies continue to find, in the Bank of the
United States, the unjust and odious privileges which they can
no longer find in the Bank of England? Shall the copy survive
here, after the original has been destroyed there? Shall the
young whelp triumph in America, after the old lion has been
throttled and strangled in England? No! never! The thing is
impossible! The Bank of the United States dies, as the Bank of
England dies, in all its odious points, upon the limitation of its
charter; and the only circumstance of regret is, that the
generous deliverance is to take effect two years earlier in the
British monarchy than in the American republic. It came to us of
war—it will go away with peace. It was born of the war of 1812
—it will die in the long peace with which the world is blessed.
The arguments on which it was created will no longer apply.
Times have changed; and the policy of the republic changes
with the times. The war made the bank; peace will unmake it.
The baleful planet of fire, and blood, and every human woe, did
bring that pestilence upon us; the benignant star of peace shall
chase it away."

This speech was not answered. Confident in its strength, and


insolent in its nature, the great moneyed power had adopted a
system in which she persevered, until hard knocks drove her out of
it: it was to have an anti-bank speech treated with the contempt of
silence in the House, and caricatured and belittled in the
newspapers; and according to this system my speech was treated.
The instant it was delivered, Mr. Webster called for the vote, and to
be taken by yeas and nays, which was done; and resulted differently
from what was expected—a strong vote against the bank—20 to 23;
enough to excite uneasiness, but not enough to pass the resolution
and legitimate a debate on the subject. The debate stopped with the
single speech; but it was a speech to be read by the people—the
masses—the millions; and was conceived and delivered for that
purpose; and was read by them; and has been complimented since,
as having crippled the bank, and given it the wound of which it
afterwards died; but not within the year and a day which would
make the slayer responsible for the homicide. The list of yeas and
nays was also favorable to the effect of the speech. Though not a
party vote, it was sufficiently so to show how it stood—the mass of
the democracy against the bank—the mass of the anti-democrats
against it. The names were:—

"Yeas.—Messrs. Barnard, Benton, Bibb, Brown, Dickerson,


Dudley, Forsyth, Grundy, Hayne, Iredell, King, McKinley,
Poindexter, Sanford, Smith of S. C., Tazewell, Troup, Tyler,
White, Woodbury—20.
"Nays.—Messrs. Barton, Bell, Burnet, Chase, Clayton, Root,
Frelinghuysen, Holmes, Hendricks, Johnston, Knight, Livingston,
Marks, Noble, Robbins, Robinson, Ruggles, Seymour, Silsbee,
Smith of Md., Sprague, Webster, Willey—23."
CHAPTER LVII.
ERROR OF DE TOCQUEVILLE, IN RELATION TO
THE HOUSE OF REPRESENTATIVES.
I have had occasion several times to notice the errors of Monsieur
de Tocqueville, in his work upon American democracy. That work is
authority in Europe, where it has appeared in several languages; and
is sought by some to be made authority here, where it has been
translated into English, and published with notes, and a preface to
recommend it. It was written with a view to enlighten European
opinion in relation to democratic government, and evidently with a
candid intent; but abounds with errors to the prejudice of that form
of government, which must do it great mischief, both at home and
abroad, if not corrected. A fundamental error of this kind—one which
goes to the root of representative government, occurs in chapter 8
of his work, where he finds a great difference in the members
comprising the two Houses of Congress, attributing an immense
superiority to the Senate, and discovering the cause of the difference
in the different modes of electing the members—the popular
elections of the House, and the legislative elections of the Senate.
He says:—

"On entering the House of Representatives at Washington,


one is struck with the vulgar demeanor of that great assembly.
The eye frequently does not discover a man of celebrity within
its walls. Its members are almost all obscure individuals, whose
names present no associations to the mind; they are mostly
village lawyers, men in trade, or even persons belonging to the
lower classes of society. In a country in which education is very
general, it is said that the representatives of the people do not
always know how to write correctly. At a few yards' distance
from this spot is the door of the Senate, which contains within a
small space a large proportion of the celebrated men in
America. Scarcely an individual is to be found in it, who does
not recall this idea of an active and illustrious career. The Senate
is composed of eloquent advocates, distinguished generals, wise
magistrates, and statesmen of note, whose language would at
all times do honor to the most remarkable parliamentary
debates of Europe. What, then, is the cause of this strange
contrast? and why are the most able citizens to be found in one
assembly rather than in the other? Why is the former body
remarkable for its vulgarity, and its poverty of talent, whilst the
latter seems to enjoy a monopoly of intelligence and of sound
judgment? Both of these assemblies emanate from the people.
From what cause, then, does so startling a difference arise? The
only reason which appears to me adequately to account for it is,
that the House of Representatives is elected by the populace
directly, and that of the Senate is elected by an indirect
application of universal suffrage; but this transmission of the
popular authority through an assembly of chosen men operates
an important change in it, by refining its discretion and
improving the forms which it adopts. Men who are chosen in
this manner, accurately represent the majority of the nation
which governs them; but they represent the elevated thoughts
which are current in the community, the generous propensities
which prompt its nobler actions, rather than the petty passions
which disturb, or the vices which disgrace it. The time may be
already anticipated at which the American republics will be
obliged to introduce the plan of election by an elected body
more frequently into their system of representation, or they will
incur no small risk of perishing miserably among the shoals of
democracy."—Chapter 8.

The whole tenor of these paragraphs is to disparage the


democracy—to disparage democratic government—to attack
fundamentally the principle of popular election itself. They disqualify
the people for self-government, hold them to be incapable of
exercising the elective franchise, and predict the downfall of our
republican system, if that franchise is not still further restricted, and
the popular vote—the vote of the people—reduced to the subaltern
choice of persons to vote for them. These are profound errors on the
part of Mons. de Tocqueville, which require to be exposed and
corrected; and the correction of which comes within the scope of
this work, intended to show the capacity of the people for self-
government, and the advantage of extending—instead of restricting
—the privilege of the direct vote. He seems to look upon the
members of the two Houses as different orders of beings—different
classes—a higher and a lower class; the former placed in the Senate
by the wisdom of State legislatures, the latter in the House of
Representatives by the folly of the people—when the fact is, that
they are not only of the same order and class, but mainly the same
individuals. The Senate is almost entirely made up out of the House!
and it is quite certain that every senator whom Mons. de Tocqueville
had in his eye when he bestowed such encomium on that body had
come from the House of Representatives! placed there by the
popular vote, and afterwards transferred to the Senate by the
legislature; not as new men just discovered by the superior sagacity
of that body, but as public men with national reputations, already
illustrated by the operation of popular elections. And if Mons. de
Tocqueville had chanced to make his visit some years sooner, he
would have seen almost every one of these senators, to whom his
exclusive praise is directed, actually sitting in the other House.
Away, then, with his fact! and with it, away with all his fanciful
theory of wise elections by small electoral colleges, and silly ones by
the people! and away with all his logical deductions, from premises
which have no existence, and which would have us still further to
"refine popular discretion," by increasing and extending the number
of electoral colleges through which it is to be filtrated. Not only all
vanishes, but his praise goes to the other side, and redounds to the
credit of popular elections; for almost every distinguished man in the
Senate or in any other department of the government, now or
heretofore—from the Congress of Independence down to the
present day—has owed his first elevation and distinction, to popular
elections—to the direct vote of the people, given, without the
intervention of any intermediate body, to the visible object of their
choice; and it is the same in other countries, now and always. The
English, the Scotch and the Irish have no electoral colleges; they
vote direct, and are never without their ablest men in the House of
Commons. The Romans voted direct; and for five hundred years—
until fair elections were destroyed by force and fraud—never failed
to elect consuls and prætors, who carried the glory of their country
beyond the point at which they had found it.
The American people know this—know that popular election has
given them every eminent public man that they have ever had—that
it is the safest and wisest mode of political election—most free from
intrigue and corruption; and instead of further restricting that mode,
and reducing the masses to mere electors of electors, they are, in
fact, extending it, and altering constitutions to carry elections to the
people, which were formerly given to the general assemblies. Many
States furnish examples of this. Even the constitution of the United
States has been overruled by universal public sentiment in the
greatest of its elections—that of President and Vice-President. The
electoral college by that instrument, both its words and intent, was
to have been an independent body, exercising its own discretion in
the choice of these high officers. On the contrary, it has been
reduced to a mere formality for the registration of the votes which
the people prepare and exact. The speculations of Monsieur de
Tocqueville are, therefore, groundless; and must be hurtful to
representative government in Europe, where the facts are unknown;
and may be injurious among ourselves, where his book is translated
into English, with a preface and notes to recommend it.
Admitting that there might be a difference between the
appearance of the two Houses, and between their talent, at the time
that Mons. de Tocqueville looked in upon them, yet that difference,
so far as it might then have existed, was accidental and temporary,
and has already vanished. And so far as it may have appeared, or
may appear in other times, the difference in favor of the Senate may
be found in causes very different from those of more or less
judgment and virtue in the constituencies which elect the two
Houses. The Senate is a smaller body, and therefore may be more
decorous; it is composed of older men, and therefore should be
graver, its members have usually served in the highest branches of
the State governments, and in the House of Representatives, and
therefore should be more experienced; its terms of service are
longer, and therefore give more time for talent to mature, and for
the measures to be carried which confer fame. Finally, the Senate is
in great part composed of the pick of the House, and therefore gains
double—by brilliant accession to itself and abstraction from the
other. These are causes enough to account for any occasional, or
general difference which may show itself in the decorum or ability of
the two Houses. But there is another cause, which is found in the
practice of some of the States—the caucus system and rotation in
office—which brings in men unknown to the people, and turns them
out as they begin to be useful; to be succeeded by other new
beginners, who are in turn turned out to make room for more new
ones; all by virtue of arrangements which look to individual interests,
and not to the public good.
The injury of these changes to the business qualities of the House
and the interests of the State, is readily conceivable, and very visible
in the delegations of States where they do, or do not prevail—in
some Southern and some Northern States, for example. To name
them might seem invidious, and is not necessary, the statement of
the general fact being sufficient to indicate an evil which requires
correction. Short terms of service are good on account of their
responsibility, and two years is a good legal term; but every
contrivance is vicious, and also inconsistent with the re-eligibility
permitted by the constitution, which prevents the people from
continuing a member as long as they deem him useful to them.
Statesmen are not improvised in any country; and in our own, as
well as in Great Britain, great political reputations have only been
acquired after long service—20, 30, 40, and even 50 years; and
great measures have only been carried by an equal number of years
of persevering exertion by the same man who commenced them.
Earl Grey and Major Cartwright—I take the aristocratic and the
democratic leaders of the movement—only carried British
parliamentry reform after forty years of annual consecutive exertion.
They organized the Society for Parliamentry Reform in 1792, and
carried the reform in 1832—disfranchising 56 burgs, half
disfranchising 31 others, enfranchising 41 new towns; and doubling
the number of voters by extending the privilege to £10 householders
—extorting, perhaps, the greatest concession from power and
corruption to popular right that was ever obtained by civil and legal
means. Yet this was only done upon forty years' continued annual
exertions. Two men did it, but it took them forty years.
The same may be said of other great British measures—Catholic
emancipation, corn law repeal, abolition of the slave trade, and
many others; each requiring a lifetime of continued exertion from
devoted men. Short service, and not popular election, is the evil of
the House of Representatives; and this becomes more apparent by
contrast—contrast between the North and the South—the caucus, or
rotary system, not prevailing in the South, and useful members
being usually continued from that quarter as long as useful; and
thus with fewer members, usually showing a greater number of men
who have attained a distinction. Monsieur de Tocqueville is
profoundly wrong, and does great injury to democratic government,
as his theory countenances the monarchial idea of the incapacity of
the people for self-government. They are with us the best and safest
depositories of the political elective power. They have not only
furnished to the Senate its ablest members through the House of
Representatives, but have sometimes repaired the injustice of State
legislatures, which repulsed or discarded some eminent men. The
late Mr. John Quincy Adams, after forty years of illustrious service—
after having been minister to half the great courts of Europe, a
senator in Congress, Secretary of State, and President of the United
States—in the full possession of all his great faculties, was refused
an election by the Massachusetts legislature to the United States
Senate, where he had served thirty years before. Refused by the
legislature, he was taken up by the people, sent to the House of
Representatives, and served there to octogenarian age—attentive,
vigilant and capable—an example to all, and a match for half the
House to the last. The brilliant, incorruptible, sagacious Randolph—
friend of the people, of the constitution, of economy and hard
money—scourge and foe to all corruption, plunder and jobbing—had
nearly the same fate; dropped from the Senate by the Virginia
general assembly, restored to the House of Representatives by the
people of his district, to remain there till, following the example of
his friend, the wise Macon, he voluntarily withdrew. I name no more,
confining myself to instances of the illustrious dead.
I have been the more particular to correct this error of De
Tocqueville, because, while disparaging democratic government
generally, it especially disparages that branch of our government
which was intended to be the controlling part. Two clauses of the
constitution—one vesting the House of Representatives with the sole
power of originating revenue bills, the other with the sole power of
impeachment—sufficiently attest the high function to which that
House was appointed. They are both borrowed from the British
constitution, where their effect has been seen in controlling the
course of the whole government, and bringing great criminals to the
bar. No sovereign, no ministry holds out an hour against the decision
of the House of Commons. Though an imperfect representation of
the people, even with the great ameliorations of the reform act of
1832, it is at once the democratic branch, and the master-branch of
the British government. Wellington administrations have to retire
before it. Bengal Governors-General have to appear as criminals at
its bar. It is the theatre which attracts the talent, the patriotism, the
high spirit, and the lofty ambition of the British empire; and the
people look to it as the master-power in the working of the
government, and the one in which their will has weight. No rising
man, with ability to acquire a national reputation, will quit it for a
peerage and a seat in the House of Lords. Our House of
Representatives, with its two commanding prerogatives and a
perfect representation, should not fall below the British House of
Commons in the fulfilment of its mission. It should not become
second to the Senate, and in the beginning it did not. For the first
thirty years it was the controlling branch of the government, and the
one on whose action the public eye was fixed. Since then the Senate
has been taking the first place, and people have looked less to the
House. This is an injury above what concerns the House itself. It is
an injury to our institutions, and to the people. The high functions of
the House were given to it for wise purposes—for paramount
national objects. It is the immediate representation of the people,
and should command their confidence and their hopes. As the sole
originator of tax bills, it is the sole dispenser of burthens on the
people, and of supplies to the government. As sole authors of
impeachment, it is the grand inquest of the nation, and has
supervision over all official delinquencies. Duty to itself, to its high
functions, to the people, to the constitution, and to the character of
democratic government, require it to resume and maintain its
controlling place in the machinery and working of our federal
government: and that is what it has commenced doing in the last
two or three sessions—and with happy results to the economy of the
public service—and in preventing an increase of the evils of our
diplomatic representation abroad.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like