How did I created a URL shortner

How did I created a URL shortner

Table of contents

No heading

No headings in the article.

In many instances you might face a situation where you need to shorten the url in order to either make it more memorable or make it look good in terms of UI. I recently faces a situation recently and my go to solution was to create an inhouse solution without using any third party dependency.

So first we need to define what we need to save since we only need to shorten the URL I have used short-uuid package in order to have it nice and clean, if your code doesn’t need to handle vast data you can use even smaller identifier.

First we need to define a model. I’m using Sequelize but the exactly same can be acheived in Any Relational or Non-Relational ORM.

const URL = sequelize.define(
  "urls",
  {
    id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    url_id: {
      type: Sequelize.STRING,
      unique: true,
    },
    url: {
      type: Sequelize.TEXT,
    },
  },
  {
    timestamps: true,
    createdAt: "created_at",
  },
);

module.exports = URL;

Now to create an entry, here is the service file for handling the creation.

const { URL } = require('../models');
const shortUUID = require("short-uuid"); // require
//...rest of the code
const createURL = async (body) => {
  if (!body.url) {
    return { error: 'No url to shorten' };
  } else {
    const { url } = body;
    const urlObj = await URL.create({
      url: url,
      url_id: shortUUID.generate(),
    });
    return { data: urlObj, success: true, message: 'URL created successfully' };
  }
};
module.exports = {
  createURL
}

and to fetch the URL you just need to pass the url_id as params and it’ll return the actual url. You can configure the frontend to take the url_id and redirect the user to the actual url.

You can put that as well in the service file.

//...Rest of the code
const getURL = async (req) => {
  if (!req.params.url_id) {
    return { error: 'url_id is required' };
  } else {
    const url_id = req.params.url_id;
    console.log(url_id);
    const urlObj = await URL.findOne({
      where: { url_id: url_id },
    });
    return { data: urlObj, success: true, message: 'URL found' };
  }
};

module.exports = {
 //...
  getURL,
};

Simple and Clean :)

The entire code for this can be found at my GitHub

Thank you for reading.

If you like this article please consider following the blog.