DEV Community

The Ghost Dev
The Ghost Dev

Posted on

MERN URL Shortener App - Part 1

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.
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:

"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:

"main": "index.js",

to

"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:

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

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

Alt Text

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.

You can follow this step-by-step guide 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:

{
  "mongouri": "mongodb+srv://priyajit:<password>@cluster0.bb04n.mongodb.net/<dbname>?retryWrites=true&w=majority"
}

Replace with your Atlas account password, and 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:

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.

// 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

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 and feel free to drop me any suggestion or just to say Hi!

Top comments (4)

Collapse
 
tradecoder profile image
Mamun Abdullah

Does valid-url identify a full url?

Collapse
 
the_ghost_dev profile image
The Ghost Dev

Yes, it does. But having said that, this module is not maintained and has few validation issues as well. Once I finish this tutorial, I will look for an alternative.

Collapse
 
tradecoder profile image
Mamun Abdullah

I became very upset with this one, what I found it just identifies upto https:// and not the next part, it accepts something like http://thisorthat where it misleads the purpose of the app. Now to see if it works with you

Thread Thread
 
the_ghost_dev profile image
The Ghost Dev

I just published the second part of this tutorial, where you can see the use of valid-url module. Please let me know if you have any question.