Build a URL Shortener with Node.js: India Tutorial

Learn to build a professional URL shortener with Node.js, Express & MongoDB—a perfect backend project for Indian students & freshers to boost their resume. Includes step-by-step coding, deployment guide, and portfolio tips.

LB
UnboxCareer Team
Editorial · Free courses curator
December 15, 20247 min read
Build a URL Shortener with Node.js: India Tutorial

Building a backend project is the single most effective way to land your first developer job in India. While everyone is polishing their DSA skills, a solid, deployable project like a URL Shortener can make your resume stand out to recruiters from TCS, Infosys, or fast-growing startups like Razorpay and Swiggy. This isn't just another tutorial; it's a blueprint for creating a portfolio piece that demonstrates real-world backend logic, database skills, and API design—exactly what hiring managers look for.

Why a URL Shortener is the Perfect Backend Project

For an Indian student or fresher, project selection is critical. You need something impressive yet achievable, and a URL Shortener hits the sweet spot. It's a recognizable product (think Bitly or TinyURL) that tackles core backend concepts without overwhelming complexity. Building one proves you can handle user input, database operations, and server logic—skills directly transferable to backend roles at companies like HCL, Accenture, or Zerodha.

This project covers essential backend pillars:

  • REST API Development: Creating endpoints to shorten URLs and redirect users.
  • Database Management: Storing original URLs, short codes, and click analytics.
  • Business Logic: Generating unique short codes and handling edge cases (like duplicate URLs).
  • Deployment: Getting your project live on a free platform, a crucial step for your portfolio.

Unlike theoretical learning, deploying this project gives you concrete talking points for interviews. You can discuss your choices, challenges faced, and how you'd scale the service—a narrative that can easily set you apart from other candidates applying for the same ₹6-10 LPA fresher roles.

Prerequisites & Tools Setup

You don't need to be an expert to start. A basic understanding of JavaScript is enough. We'll use the Node.js runtime and the Express.js framework, the backbone for countless backend services in India's tech ecosystem.

Here’s your toolkit:

  1. Node.js & npm: Download and install the LTS version from the official website. Verify installation by running node --version and npm --version in your terminal.
  2. A Code Editor: VS Code is highly recommended and free.
  3. MongoDB Database: We'll use MongoDB Atlas, a free cloud database service, so no complex local setup is needed.
  4. Postman: A free tool to test our APIs. You can also use Thunder Client in VS Code.

To initialize your project, open your terminal, create a new directory, and follow these steps:

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

This creates a package.json file. Now, install the necessary packages:

npm install express mongoose shortid
  • express: The web framework.
  • mongoose: An ODM (Object Data Modeling) library for MongoDB.
  • shortid: A simple package to generate unique short codes for our URLs.

Your foundation is now ready.

Building the Core Backend Logic

Let's break down the construction into logical steps. First, create an index.js file as your application's entry point.

Step 1: Setting Up the Express Server

Start by requiring the modules and setting up a basic server that listens on port 3000.

const express = require('express');
const mongoose = require('mongoose');
const ShortUrl = require('./models/shortUrl'); // We'll create this model next
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Connect to MongoDB Atlas (replace <password> with your actual password)
mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/urlShortener', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Step 2: Creating the MongoDB Data Model

Create a models folder and inside it, a shortUrl.js file. This defines the structure of the data we will save.

const mongoose = require('mongoose');

const shortUrlSchema = new mongoose.Schema({
  full: {
    type: String,
    required: true
  },
  short: {
    type: String,
    required: true,
    unique: true
  },
  clicks: {
    type: Number,
    required: true,
    default: 0
  }
});

module.exports = mongoose.model('ShortUrl', shortUrlSchema);

This schema stores the original (full) URL, the generated short code, and a count of clicks for basic analytics.

Step 3: Implementing the Shortening Endpoint

Now, back in index.js, we'll create the POST API endpoint that takes a long URL and returns a short one.

const shortId = require('shortid');

app.post('/shorten', async (req, res) => {
  const { fullUrl } = req.body;

  // Check if URL already exists in DB to avoid duplicates
  const existingUrl = await ShortUrl.findOne({ full: fullUrl });
  if (existingUrl) {
    return res.json(existingUrl);
  }

  // Create and save a new short URL entry
  const shortUrl = await ShortUrl.create({
    full: fullUrl,
    short: shortId.generate() // Generates a unique short code
  });

  res.json(shortUrl);
});

You can test this endpoint in Postman by sending a POST request to http://localhost:3000/shorten with a JSON body { "fullUrl": "https://www.example.com/very-long-path" }.

Step 4: Creating the Redirect Endpoint

The core functionality is the redirect. We need a GET endpoint that finds the short code and redirects the user 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); // Not found
  }

  shortUrl.clicks++; // Increment the click counter
  await shortUrl.save();

  res.redirect(shortUrl.full); // Perform the redirect
});

With this, your basic URL shortener backend is functional! You can shorten a URL via the /shorten endpoint and access it via http://localhost:3000/<short-code>.

Adding Essential Features & Polish

A basic shortener works, but to make it portfolio-ready, we need to add features that show deeper understanding.

While the focus is backend, a minimal HTML form makes testing intuitive and shows full-stack awareness. Create a public folder and an index.html file inside it. Serve static files by adding this line to index.js before your routes:

app.use(express.static('public'));

Your HTML can have a form that POSTs to your /shorten endpoint and displays the generated short link.

2. Input Validation & Error Handling

Never trust user input. Add validation to ensure the submitted string is a valid URL. You can use a package like valid-url.

npm install valid-url

Then, modify your /shorten endpoint:

const validUrl = require('valid-url');

app.post('/shorten', async (req, res) => {
  const { fullUrl } = req.body;

  if (!validUrl.isUri(fullUrl)) {
    return res.status(400).json({ error: 'Invalid URL provided' });
  }
  // ... rest of the code
});

3. Viewing Click Analytics

Create a GET endpoint (e.g., /analytics/:shortUrl) that returns the click data for a short URL. This demonstrates your ability to create analytical endpoints, a common task in backend development for products at Flipkart or Paytm.

Deployment: Getting Your Project Live

A project on localhost has limited value. Deploying it makes it accessible to everyone and is a non-negotiable point on a good resume. For Indian students, free tiers are a blessing.

  1. Push your code to GitHub. Make sure to include a .gitignore file for node_modules.
  2. Choose a hosting platform. Render or Cyclic offer excellent free tiers for Node.js apps with MongoDB integration. Heroku is another option, though its free tier is now limited.
  3. Configure Environment Variables. Move your MongoDB connection string and other secrets out of your code into environment variables provided by the hosting platform. Use the dotenv package locally.
  4. Deploy. Connect your GitHub repository to your chosen platform. It will build and deploy your application, giving you a live URL (e.g., https://your-app.onrender.com).

Now, you have a live, functional backend API. This is a tangible asset.

Common Challenges & How to Debug Them

You will face errors—it's part of the learning. Here are common ones and their fixes:

  • MongoDB Connection Error: Double-check your Atlas connection string. Ensure your IP is whitelisted in the Atlas network access settings.
  • shortId is not unique: While rare, you can add a check before saving to ensure the generated short code doesn't already exist in the database.
  • CORS Errors: If you build a separate frontend, you'll need to handle CORS. Install the cors package (npm install cors) and use it as middleware: app.use(require('cors')()).
  • Application Crashes on Render/Heroku: Check the platform's logs. Often, the issue is a missing "start" script in your package.json. Ensure it looks like this: "start": "node index.js".

Use console.log() statements liberally and learn to read terminal error messages. Following Indian tech creators like CodeWithHarry or Apna College on YouTube can provide visual debugging guidance for similar projects.

Next Steps

You've built a solid foundation. To truly level up this project and your skills, consider these enhancements. First, explore more advanced backend projects to understand different system designs. Next, deepen your database knowledge by learning about indexing for faster lookups—a key optimization topic. Finally, browse free, structured courses on Node.js and MongoDB from platforms like NPTEL, Coursera (with Financial Aid), and freeCodeCamp to fill any conceptual gaps and build with even more confidence.

Keep learning on UnboxCareer

Explore free courses, certificates, and career roadmaps curated for Indian students.