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
})
- What is your thought about this code?
- Will that work when thousands of clicks at the same time?
- Any improvements that I can do to increase the redirection time?
Thanks for your time. ❤️
navigator
is likelyundefined
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\$