Reader small image

You're reading from  Full-Stack React Projects. - Second Edition

Product typeBook
Published inApr 2020
Reading LevelBeginner
PublisherPackt
ISBN-139781839215414
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Shama Hoque
Shama Hoque
author image
Shama Hoque

Shama Hoque has 8 years of experience as a software developer and mentor, with a Master's in Software Engineering from Carnegie Mellon University. From Java programming to full-stack development with JavaScript, the applications she has worked on include national Olympiad registration websites, universally accessible widgets, video conferencing apps, and medical 3D reconstruction software. Currently, she makes web-based prototypes for R&D start-ups in California, while training aspiring software engineers and teaching web development to CS undergrads in Bangladesh.
Read more about Shama Hoque

Right arrow

Building a Backend with MongoDB, Express, and Node

While developing different web applications, you will find there are common tasks, basic features, and implementation code repeated across the process. The same is true for the MERN applications that will be developed in this book. Taking these similarities into consideration, we will first lay the foundations for a skeleton MERN application that can be easily modified and extended to implement a variety of MERN applications.

In this chapter, we will cover the following topics and start with the backend implementation of the MERN skeleton using Node, Express, and MongoDB:

  • Overview of the skeleton application
  • Backend code setup
  • User model with Mongoose
  • User CRUD API endpoints with Express
  • User Auth with JSON Web Tokens
  • Running backend code and checking APIs

Overview of the skeleton application

The skeleton application will encapsulate rudimentary features and a workflow that's repeated for most MERN applications. We will build the skeleton as a basic but fully functioning MERN web application with user create, read, update, delete (CRUD), and authentication-authorization (auth) capabilities; this will also demonstrate how to develop, organize, and run code for general web applications built using this stack. The aim is to keep the skeleton as simple as possible so that it is easy to extend and can be used as a base application for developing different MERN applications.

Feature breakdown

In the skeleton application, we will add the following use cases with user CRUD and...

Setting up the skeleton backend

To start developing the backend part of the MERN skeleton, we will set up the project folder, install and configure the necessary Node modules, and then prepare run scripts to aid development and run the code. Then, we will go through the code step by step to implement a working Express server, a user model with Mongoose, API endpoints with Express router, and JWT-based auth to meet the specifications we defined earlier for user-oriented features.

The code that will be discussed in this chapter, as well as the complete skeleton application, is available on GitHub at https://github.com/PacktPublishing/Full-Stack-React-Projects-Second-Edition/tree/master/Chapter03%20and%2004/mern-skeleton . The code for just the backend is available at the same repository in the branch named mern2-skeleton-backend. You can clone this code and run the application as...

Implementing the user model

We will implement the user model in the server/models/user.model.js file and use Mongoose to define the schema with the necessary user data fields. We're doing this so that we can add built-in validation for the fields and incorporate business logic such as password encryption, authentication, and custom validation.

We will begin by importing the mongoose module and use it to generate a UserSchema, which will contain the schema definition and user-related business logic to make up the user model. This user model will be exported so that it can be used by the rest of the backend code.

mern-skeleton/server/models/user.model.js:

import mongoose from 'mongoose'

const UserSchema = new mongoose.Schema({ … })

export default mongoose.model('User', UserSchema)

The mongoose.Schema() function takes a schema definition object as a...

Adding user CRUD APIs

The user API endpoints exposed by the Express app will allow the frontend to perform CRUD operations on documents that are generated according to the user model. To implement these working endpoints, we will write Express routes and the corresponding controller callback functions that should be executed when HTTP requests come in for these declared routes. In this section, we will look at how these endpoints work without any auth restrictions.

Our user API routes will be declared using the Express router in server/routes/user.routes.js, and then mounted on the Express app we configured in server/express.js.

mern-skeleton/server/express.js:

import userRoutes from './routes/user.routes'
...
app.use('/', userRoutes)
...

All routes and API endpoints, such as the user-specific routes we'll declare next, need to be mounted on the Express...

Integrating user auth and protected routes

To restrict access to user operations such as user profile view, user update, and user delete, we will first implement sign-in authentication with JWT, then use it to protect and authorize the read, update, and delete routes.

The auth-related API endpoints for sign-in and sign-out will be declared in server/routes/auth.routes.js and then mounted on the Express app in server/express.js.

mern-skeleton/server/express.js:

import authRoutes from './routes/auth.routes'
...
app.use('/', authRoutes)
...

This will make the routes we define in auth.routes.js accessible from the client-side.

Auth routes

The two auth APIs are defined in the auth.routes.js file using express...

Checking the standalone backend

There are a number of options when it comes to selecting tools to check backend APIs, ranging from the command-line tool curl (https://github.com/curl/curl) to Advanced REST Client (ARC) (https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo), a Chrome extension app with an interactive user interface.

To check the APIs that were implemented in this chapter, first, have the server running from the command line and use either of these tools to request the routes. If you are running the code on your local machine, the root URL is http://localhost:3000/.

Using ARC, we will showcase the expected behavior for five use cases so that we can check the implemented API endpoints.

Creating a new user

...

Summary

In this chapter, we developed a fully functioning standalone server-side application using Node, Express, and MongoDB and covered the first part of the MERN skeleton application. In the backend, we implemented a user model for storing user data, implemented with Mongoose; user API endpoints to perform CRUD operations, which were implemented with Express; and user auth for protected routes, which was implemented with JWT and express-jwt.

We also set up the development flow by configuring Webpack so that it compiles ES6+ code using Babel. We also configured Nodemon so that it restarts the server when the code changes. Finally, we checked the implementation of the APIs using the Advanced Rest API Client extension app for Chrome.

Now, we are ready to extend this backend application code and add the React frontend, which will complete the MERN skeleton application. We will...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full-Stack React Projects. - Second Edition
Published in: Apr 2020Publisher: PacktISBN-13: 9781839215414
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Shama Hoque

Shama Hoque has 8 years of experience as a software developer and mentor, with a Master's in Software Engineering from Carnegie Mellon University. From Java programming to full-stack development with JavaScript, the applications she has worked on include national Olympiad registration websites, universally accessible widgets, video conferencing apps, and medical 3D reconstruction software. Currently, she makes web-based prototypes for R&D start-ups in California, while training aspiring software engineers and teaching web development to CS undergrads in Bangladesh.
Read more about Shama Hoque