I want to create a service to track affiliate link clicks. The logic is simple, When a user is clicked on the link provided by the service will redirect to an original affiliate link.

I stored data in MongoDB. I want to get the original affiliate link bypassing the offerID(Service provided offerID).

I wrote the following code:

app.get('/click', async (req, res) => {

    //Tracking link : https://myservice.com/click?a=500&o=15112

    const url =req.protocol + '://' + req.get('host') + req.originalUrl
    const affiliateId = new URL(url).searchParams.get('a')
    const offerID = new URL(url).searchParams.get('o')
    //Getting affiliateID and offerID from URL

    const link = await Links.findOne({oID: offerID}) //Getting the affiliate link from the MongoDB by passing offerID
    if (link == null) return res.sendStatus(404)

    const userAgent =  navigator.userAgent //Getting the userAgent
    const clickID = shortId.generate //Generating a unique clickID
    const finalLink = link.affiliateLink.concat(`&clickID=${clickID}&sub1=${affiliateId}`) //Creating the link from the affiliates
    //Link will be like https://offer.com/clicks?affiliateoffer=500&affiliateid=1000&clickID=12151212121&sub1=500

    const click = new Click({
        affID: affiliateId,
        oID: offerID,
        clickID: clickID,
        userAgent: userAgent,

    Click.save(click) // Saving the click on the database(mongodb)
    res.redirect(finalLink) //Redirecting to affiliate link
  1. What is your thought about this code?
  2. Will that work when thousands of clicks at the same time?
  3. Any improvements that I can do to increase the redirection time?

Thanks for your time. ❤️

  • \$\begingroup\$ Welcome to Code Review! Have you tested this code? Correct me if I am wrong but navigator is likely undefined in the NodeJs code, unless that is set by some other code like a middleware function. See this related SO answer and also this one. \$\endgroup\$ Dec 17, 2022 at 8:43


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.