MERN URL Shortener App - Part 1
Tags: react, node, mongodb, express
Published: 2020-07-06 21:06:24

In this multi-part tutorial, we will work together to build an URL Shortener app (basic version of bitly) using React, NodeJS, Express and MongoDB. This will be basically a full-stack application build with MERN stack.

We will be learning Context API, Hooks, Express router, and building a Custom API With JWT Authentication.

Prerequisites: You should know JavaScript pretty well, including ES6 (Arrow functions, promises, etc) and basic understanding/knowledge of React, Node & Express.

Let's jump in then...


## Step 1 - Modules Installation

Initializing package.json for backend:

Run `npm init` and add all the details as per your choice.

Install the required backend Modules:

1. express - NodeJS application framework
2. express-validator - It is an Express middleware to validate input form fields
3. mongoose - a MongoDB client
4. config - this makes a lot easier to deal with NodeJS config files
5. shortid - short non-sequential url-friendly unique id generator
6. valid-url - This module collects common URI validation routines to make input validation
7. bcryptjs - This is useful for generating and verifying hash password
8. jswebtoken - This generates a token useful for validating logged in user
9. nodemon - tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.


```javascript
npm i express express-validator mongoose config shortid valid-url bcryptjs jsonwebtoken

npm i -D nodemon
```
To setup nodemon, we need to edit `package.json` file, and replace `test` script as below:

```json
"scripts": {
    "start": "npm server",
    "dev": "nodemon server"
  }
```

_Note: If you've selected all the default. options while initializing NPM, then you've probably set index.js as your main file. But in this tutorial we will be using server.js as our main file, so you can replace `index.js` with `server.js` by replacing it in the above `package.json` file. Change the below part:_

```json
"main": "index.js",
```
to
```json
"main": "server.js",
```

## Step 2 - Express setup

In the root directory, create a file `server.js`. This will be our main file for the backend.

Let's configure Express on our `server.js` file:

```javascript
const express = require('express'); // Loading Express module

// Initialize Express
const app = express();

// Initialize JSON body parser
app.use(express.json());

// Add Express Port
const PORT = process.env.port || 5000;

// Returns response (for testing)
app.use('/', (request, response) => response.send('Hello'));

// Start Express
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
```

We can now start Express:

On our Terminal, while in the `url-shortener` directory, run `npm start dev`. This will now start Express. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z4wmv6v2agqgzeuxmjpz.png)

But to test it, we need an HTTP API testing tool, like Postman.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/s4d14d4xe4gdjt4xhkd5.png)

In the above screenshot, on Postman, I have added my path `http"//localhost:5000/` as GET request. Now when I hit send, it returned the text `Hello` in the body, that we have set on our `server.js`. 

## Step 3 - MongoDB setup

Create a `config` directory in root directory, and inside that create a file `db.js` and `default.json`. 

Create a database on MongoDB Atlas [here](https://www.mongodb.com/cloud/atlas). 

You can follow this step-by-step [guide](https://www.knowi.com/blog/getting-started-with-mongodb-atlas-overview-and-tutorial/) for easily creating your account and getting the connection string which will be required in the next step for connecting to the database.

We now need to add the MongoDB URI, that you copied from Atlas  to our config file. Let's open our `default.json` file that we created on the above step, and paste the MongoDB URI as below:

```json
{
  "mongouri": "mongodb+srv://priyajit:<password>@cluster0.bb04n.mongodb.net/<dbname>?retryWrites=true&w=majority"
}
```
Replace <password> with your Atlas account password, and <dbname> with your database name that you have created on Atlas.

Now open `db.js` file, which is our MongoDB configuration file. Let's set it up:

```javascript
const mongoose = require('mongoose'); // Loading Mongoose module
const config = require('config'); // Loading config module

const db = config.get('mongouri'); // Fetching MongoDB URL from config.json

// Function to Connect MongoDB
const connectDB = async () => {
  try {
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
    });

    console.log('Database Connected Successfully...');
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};

module.exports = connected; // Exporting module so that we can import it on server.js
```

We now have to call the function to connect database on our `server.js` file. We can add the function just below where we are initializing express. 

```javascript
// Initialize Express
const app = express();

// Connect Database
const connectDB = require('./config/db');
connectDB();
```

Now you can run Express and connect to your database by running `npm run dev` on your terminal. If all goes well, you should see this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u1utepvwb66tpxh653vo.png)

We have now successfully set up Express that is connected with MongoDB Atlas database.

In the next part, we will setup our Express routes and database models.




Follow me on [Twitter](https://twitter.com/the_ghost_dev) and feel free to drop me any suggestion or just to say Hi!