Building a URL Shortener with Node.js and JavaScript

By | 6 months ago

javainterviewjobsnode backenddot netkerala itsystem designurl shortner careers

# Building a URL Shortener with Node.js and JavaScript

Introduction

URL shorteners are a popular tool across the web, turning long URLs into manageable, short links that are easier to share. In this tutorial, we'll build a simple URL shortener from scratch using Node.js and JavaScript, including the backend service and a basic front-end.

Why Build a URL Shortener?

URL shorteners can enhance user experience by reducing the length of URLs, making them easier to type and share, especially on platforms with character limits. They also allow for tracking and analyzing data about link engagement and performance.

Tech Stack

  • **Node.js**: For the server-side logic.

  • **Express**: A minimal and flexible Node.js web application framework.

  • **MongoDB**: A NoSQL database to store URL mappings.

  • **Mongoose**: An ODM (Object Data Modeling) library for MongoDB and Node.js.

Setting Up Your Project

Step 1: Initialize Node.js Project

Create a new directory for your project and initialize a Node.js application:

mkdir my-url-shortener cd my-url-shortener npm init -y

Step 2: Install Dependencies

Install the required NPM packages:

npm install express mongoose shortid
  • `express` for handling HTTP requests.

  • `mongoose` for database interactions.

  • `shortid` to generate short, unique IDs for URLs.

Implementing the URL Shortener

Step 1: Set Up the Server

Create a file called `server.js` and set up a basic Express server:

const express = require('express'); const mongoose = require('mongoose'); const ShortUrl = require('./models/shortUrl'); const app = express(); app.use(express.urlencoded({ extended: false })); mongoose.connect('mongodb://localhost/urlShortener', { useNewUrlParser: true, useUnifiedTopology: true }); app.get('/', async (req, res) => { const shortUrls = await ShortUrl.find(); res.send(shortUrls); }); app.post('/shortUrls', async (req, res) => { await ShortUrl.create({ full: req.body.fullUrl }); res.redirect('/'); }); app.listen(process.env.PORT || 5000);

Step 2: Create URL Model

Create a new directory called models, and inside it, create a file named shortUrl.js:

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);

Step 3: Redirect Logic

Add a route to handle redirection from a short URL to the original URL:

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); });

Testing the Application

Run your server with `node server.js, and test the application by accessing http://localhost:5000\` in your browser. You can create new short URLs and use them to redirect to the original URLs.

Conclusion

Congratulations! You've just created a basic URL shortener with Node.js. This project can be expanded with additional features such as user authentication, detailed analytics, custom URL slugs, and more.

Next Steps

  • Enhance the front-end using frameworks like React or Angular.

  • Implement additional security features to prevent abuse.

  • Deploy your application using services like Heroku or AWS.