How to track visits or clicks on an Url shortener using ExpressJS and NodeJS?

173 views Asked by At

I'm working on a URL shortener for learning purposes, and I want to add a way to track the clicks or visits for each shortened URL.

An example of a shortened URL from my app is this: http://localhost:3000/384oxt where the code 384oxt is saved in my database and is related to the URL: https://www.google.com/.

So, when the user visits: http://localhost:3000/384oxt, I have this method to do the redirect:

const redirect = async (req, res) => {
  const { code } = req.params;

  if (!code || !(await ShortenedUrl.existsUrlCode(code))) {
    return res.status(404).json({
      status: 'err',
      errors: [
        {
          message: "The urlCode doesn't exist",
        },
      ],
    });
  }

  try {
    const shortenedUrl = await ShortenedUrl.findOne({ urlCode: code }).exec();
    console.log(req);
    return res.redirect(301, shortenedUrl.source);
  } catch (err) {
    console.error(err);

    return res.status(500).json({
      status: 'err',
      errors: [{ message: 'A problem has occurred, please try again' }],
    });
  }
};

As you can see, I get the code, then I check if the code exists in the database, if not, I return a response with the message error, but if the code exists, I get from the database the URL that is linked to that code and I do the redirect.

The first time, it works OK, and this instruction: console.log(req); prints the request on the console.

But if I use the same shortened URL again: http://localhost:3000/384oxt, it seems like the browser is doing the redirect without entering the redirect method in my NodeJS app. The instruction console.log(req); is not printed anymore. Even if I delete the method, the redirect still works.

I want to store some statistics like the browser, time, etc when someone uses the shortened URL, but with this behavior, I can't.

How can I force that every time the shortener URL is used the method is executed?

0

There are 0 answers