profile

Design a URL shortening service using Node.js with Express and a MongoDB database.

Here’s how you can design a URL shortening service using Node.js with Express and a MongoDB database.

1. Set Up the Environment

First, ensure you have Node.js and MongoDB installed. Create a new Node.js project and install the necessary dependencies:

mkdir url-shortener
cd url-shortener
npm init -y
npm install express mongoose shortid

2. Create the Project Structure

url-shortener/
│
├── server.js
├── models/
│   └── url.js
└── routes/
    └── urlRoutes.js

3. Define the URL Model

Create a url.js file in the models directory to define the URL schema:

// models/url.js
const mongoose = require("mongoose");
const shortid = require("shortid");
const urlSchema = new mongoose.Schema({
  originalUrl: { type: String, required: true },
  shortUrl: { type: String, required: true, default: shortid.generate },
});
module.exports = mongoose.model("URL", urlSchema);

4. Set Up Routes

Create urlRoutes.js in the routes directory to handle the API endpoints:

// routes/urlRoutes.js
const express = require("express");
const router = express.Router();
const URL = require("../models/url");
router.post("/shorten", async (req, res) => {
  const { originalUrl } = req.body;
  let url = await URL.findOne({ originalUrl });
  if (url) {
    res.json({ shortUrl: url.shortUrl });
  } else {
    url = new URL({ originalUrl });
    await url.save();
    res.json({ shortUrl: url.shortUrl });
  }
});
router.get("/:shortUrl", async (req, res) => {
  const { shortUrl } = req.params;
  const url = await URL.findOne({ shortUrl });
  if (url) {
    res.redirect(url.originalUrl);
  } else {
    res.status(404).json("URL not found");
  }
});
module.exports = router;

5. Set Up the Server

Create server.js to set up the Express server and connect to MongoDB:

// server.js
const express = require("express");
const mongoose = require("mongoose");
const urlRoutes = require("./routes/urlRoutes");
const app = express();
app.use(express.json());
app.use("/", urlRoutes);
mongoose
  .connect("mongodb://localhost/urlShortener", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected to MongoDB");
    app.listen(3000, () => {
      console.log("Server running on port 3000");
    });
  })
  .catch((err) => {
    console.error("Error connecting to MongoDB", err);
  });

6. Run the Application

Start the server by running:

node server.js

Final Thoughts

This setup provides a simple URL shortening service using Node.js, Express, and MongoDB. The service features two endpoints: one for shortening URLs and another for redirecting from short URLs to the original URLs. This is a basic implementation, and you can further enhance it by adding features such as user authentication, custom short URLs, analytics, and more robust error handling.