How to make a URL shortener

In this tutorial, we are gonna make a perfect URL shortener for your project using Nodejs, Express, and MongoDB.

3 min read

In this tutorial, we are gonna make a perfect URL shortener for your project using Nodejs, Express, and MongoDB.

Prerequisites

  1. Nodejs installed
  2. NPM package manager CLI installed
  3. MongoDB installed on your machine

Structure of our project

url-shortener/
|── models/
|    ├── shortUrl.js
|
|── views/
|    |── index.ejs
|
|── index.js
|
|── package-lock.json
|
└── package.json

Create a package.json file for this project

Create a package.json file in the root directory of your project. After that cd in your project from the command line and run the npm install command. It will install all the dependencies we are gonna use in this project.

{
  "name": "url-shortener",
  "version": "1.0.0",
  "description": "Url shortener for your project using nodejs, express and mongodb.",
  "main": "index.js",
  "engines": {
    "node": "12.19.0",
    "npm": "6.14.8"
  },
  "scripts": {
    "start": "node index.js",
    "thelovekesh": "nodemon index.js"
  },
  "author": "Lovekesh Kumar",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.5",
    "express": "^4.17.1",
    "mongoose": "^5.10.9",
    "shortid": "^2.2.15"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  }
}
package.json file for project

Create an index.js file in your project root directory

const express = require("express");
const mongoose = require("mongoose");
const shortUrl = require("./models/shortUrl");
const ShortUrl = require("./models/shortUrl");
const app = express();

mongoose.connect(
    //your database connection string here
    "mongodb://localhost/urlShortner", {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    }
);

app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: false }));

app.get("/", async(req, res) => {
    const shortUrls = await ShortUrl.find();
    res.render("index", { shortUrls: shortUrls });
});

app.post("/shortUrls", async(req, res) => {
    await ShortUrl.create({ full: req.body.fullUrl });

    res.redirect("/");
});

app.get("/:shortUrl", async(req, res) => {
    const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl });

    if (shortUrl == null) return res.sendStatus(404);

    shortUrl.clicks++;
    shortUrl.save();

    res.redirect(shortUrl.full);
});

app.listen(process.env.PORT || 5000);
console.log(`app is running at http://localhost:5000`);
index.js file for project

Create a shortUrl.js file inside models folder

const mongoose = require("mongoose");
const shortId = require("shortid");

const shortUrlSchema = new mongoose.Schema({
  full: {
    type: String,
    required: true,
  },

  short: {
    type: String,
    required: true,
    default: shortId.generate,
  },
  clicks: {
    type: Number,
    required: true,
    default: 0,
  },
});

module.exports = mongoose.model("ShortUrl", shortUrlSchema);
shortUrl.js file for project

Create an index.ejs file inside views folder

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="description" content="A perfect url shortner for your project." />
  <title>Url Shortner</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
    integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
</head>

<body>
  <div class="container-xl">
    <h1 class="text-center mb-5">
      Url Shortener
      <span class="pb-1 h3">by
        <a href="http://twitter.com/thelovekesh" target="_blank" rel="noopener noreferrer">thelovekesh</a></span>
    </h1>
    <section class="col-12">
      <form action="/shortUrls" method="POST" class="my-4 form-inline">
        <div class="form-group mb-2">
          <label for="fullUrl" class="sr-only">Url</label>
          <input type="url" class="form-control bordered" name="fullUrl" id="fullUrl" placeholder="Type Url" />
        </div>
        <button type="submit" class="btn btn-info mb-2">Shrink</button>
      </form>
    </section>

    <section>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">Long Url</th>
            <th scope="col">Short Url</th>
            <th scope="col">Clicks</th>
          </tr>
        </thead>
        <tbody>
          <% shortUrls.forEach(shortUrl => { %>
          <tr>
            <td><a href="<%= shortUrl.full %>"><%= shortUrl.full %></a></td>
            <td><a href="<%= shortUrl.short %>"><%= shortUrl.short %></a></td>
            <td><%= shortUrl.clicks %></td>
          </tr>
          <% }) %>
        </tbody>
      </table>
    </section>
  </div>
  
</body>
</html>
index.ejs file for project

After completing all the steps run the command npm run thelovekesh and the project will start at http://localhost:5000


GitHub Code Repository

thelovekesh/url-shortner
In this tutorial, we are gonna make a perfect URL shortener for your project using Nodejs, Express, and MongoDB. - thelovekesh/url-shortner
Download code from here

Live Demo


Make a URL shortener using Nodejs, Express, and MongoDB

In this tutorial, we are gonna make a perfect URL shortener for your project using Nodejs, Express, and MongoDB.

3 min read

How to send HTML form data without server-side coding

Sending your form data and manage it can be a very tricky process. In this tutorial, we will send our website's form data to Google sheets without any server-side coding.

4 min read