My main function is I am creating a link-shortening app. When someone entered a long URL, it will give a short URL. If the user clicked on the short link it will search for the long URL on the DB and redirect it to the long URL.
Meantime I want to get the click count and clicked user’s OS.
I am currently using current code :
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
if (shortUrl == null) return res.sendStatus(404)
res.redirect(shortUrl.full)
})
findOne is finding the Long URL on the database using ShortID. I used mongoDB here
My questions are :
- Are there multiple redirect methods in JS?
- Is this method work if there is a high load?
- Any other methods I can use to achieve the same result?
- What other facts that matter on redirect time
- What is ‘No Redirection Tracking’?
This is a really long question, Thanks to those who invested their time in this.
2
Answers
First off, there are no redirect methods in Javascript.
res.redirect()
is a feature of the Express http framework that runs in nodejs. This is the only method built into Express, though all a redirect response consists of is a 3xx (often 302) http response status and setting theLocation
header to the redirect location. You can manually code that just as well as you can useres.redirect()
in Express.You can look at the
res.redirect()
code in Express here.The main things it does are set the location header with this:
And set the http status (which defaults to 302) with this:
Then, the rest of the code has to do with handling variable arguments, handling an older design for the API and sending a body in either plain text or html (neither of which is required).
res.redirect()
works just fine at a high load. The bottleneck in your code is probably this line of code:And, how high a scale that goes to depends upon a whole bunch of things about your database, configuration, hardware, setup, etc… You should probably just test how many request/sec of this kind your current database can handle.
Sure there are. But, you will have to use some data store to look up the shortUrl to find the long url and you will have to create a 302 response somehow. As said earlier, the scale you can achieve will depend entirely upon your database.
This is pretty much covered above (hint, its all about the database).
You can read about it here on MDN.
Your code is ok, the only limitation is where you run it and mongodb.
I have created apps that are analytics tracker, handling billion rows per day.
I suggest you run your node code using AWS Beanstalk APP. It has low latency and scales on your needs.
And you need to put redis between your request and mongodb, you will call mongodb only if your data is not yet in redis. Mongodb has more read limitations than a straight redis instance.