Creating Your Own URL Shortener with Node.js
Javascript Nodejs

Creating Your Own URL Shortener with Node.js

5 min read

URL shorteners are a useful tool for making long, complex URLs shorter and easier to share. In this tutorial, we will be creating a URL shortener using JavaScript.

To create a URL shortener, we will be using Node.js and the Express framework. Node.js is a server-side JavaScript platform that allows us to run JavaScript code outside of the web browser. Express is a fast and minimalist web framework for Node.js that provides a set of features for building web applications.

Let’s jump in!

Step 1: Setup

Before we get started, we need to set up our project. To do this, create a new directory for your project and run the following command in the terminal:

npm init -y

This command will initialize a new Node.js project and create a package.json file in your project directory.

Next, we need to install the required dependencies. Run the following command in the terminal:

npm install express shortid

This command will install express and shortid, which is a library for generating unique IDs.

Step 2: Creating the server

In this step, we will create the server using Express. Create a new file called server.js in your project directory and add the following code:

const express = require('express');
const shortId = require('shortid');

const app = express();

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

The code imports express and shortid, defines app, and then starts the server on port 3000, logging a message to the console to confirm that the server has started.

Step 3: Creating the URL Shortener

Now that we have set up the server, we can create the URL shortener. Add the following code to server.js:

...

const urls = {};

app.get('/shorten', (req, res) => {
  const url = req.query.url;
  const id = shortId.generate();

  urls[id] = url;

  res.send(`http://localhost:3000/${id}`);
});

app.get('/:id', (req, res) => {
  const id = req.params.id;
  const url = urls[id];

  if (url) {
    res.redirect(url);
  } else {
    res.sendStatus(404);
  }
});

...

This code imports the shortid library and creates an empty object called urls to store the original URLs and their corresponding shortened URLs.

The first route we defined handles the URL shortening.

When a GET request is made to /shorten with a url query parameter, the code generates a unique ID using the shortid library and stores the original URL in the urls object with the ID as the key. It then sends the shortened URL back to the client as a response.

The second route handles the redirection from the shortened URL to the original URL. When a GET request is made to /:id, the code retrieves the original URL from the urls object using the ID from the URL parameter. If the original URL exists, the code redirects the client to the original URL. Otherwise, it sends a 404 status code.

Step 4: Testing the URL shortener

To test the URL shortener, start the server by running the following command in the terminal:

node server.js

Open your web browser and go to http://localhost:3000/shorten?url=https://blog.javascripttoday.com. This will generate a shortened URL and display it in your browser.

You can then copy the shortened URL and paste it into your browser to test the redirection. This should redirect you to the original URL.

Complete Implementation

const express = require('express');
const shortId = require('shortid');

const app = express();

const urls = {};

app.get('/shorten', (req, res) => {
  const url = req.query.url;
  const id = shortId.generate();

  urls[id] = url;

  res.send(`http://localhost:3000/${id}`);
});

app.get('/:id', (req, res) => {
  const id = req.params.id;
  const url = urls[id];

  if (url) {
    res.redirect(url);
  } else {
    res.sendStatus(404);
  }
});


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

Conclusion

In this tutorial, we have learned how to build a simple URL shortener using JavaScript and Node.js. We have covered the basics of routing, and generating unique IDs.

There are many ways to improve this URL shortener, of which we will be covering over the next few articles, where we will add error handling, a front-end, and finally, we will deploy the application.

As for the front-end, what would you like us to use (e.g. React, Vue, Angular, keep it simple with plain HTML)? Let us know in the comments!

And of course, our ebook is available at 70% off: The Impatient Programmer’s Guide to JavaScript. Thank you for the support!

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Learn AI Skills with Codecademy (729x90)

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.