How to Build a URL Forwarding Service: A Step-by-Step Guide
A URL forwarding service takes a short slug (like bit.ly/abc) and redirects users to a longer destination URL. Building your own is straightforward using Node.js and a simple database. This guide walks you through creating a minimal yet functional service.
You’ll need Node.js installed, a text editor, and basic knowledge of JavaScript. We’ll use Express for routing and a lightweight JSON file for storage (upgrade to SQLite or PostgreSQL for production).
1. Set Up Your Server
Initialize a new Node.js project and install Express:
npm init -ynpm install express
Create an index.js file with a basic Express app listening on port 3000.
2. Create a Database for URL Mappings
Use a JSON file (e.g., mappings.json) to store slug-destination pairs. Initialize it with an empty object. For each new mapping, write a unique slug and the target URL.
3. Build the Redirect Endpoint
Add a GET route with a parameter for the slug: app.get('/:slug', ...). Inside, read the JSON file, look up the slug, and respond with res.redirect(302, url). If the slug doesn’t exist, return a 404 page.
4. Add URL Creation Endpoint
Create a POST endpoint /create that accepts a url body. Generate a random 6-character slug (or let the user provide one). Save the mapping to the JSON file and return the full shortened URL.
That’s it! Test your service locally: POST a URL, get a short link, then visit it in the browser — you’ll be redirected. For production, use a database, add analytics, and deploy to a cloud platform like Heroku or Vercel.