by gregdoesit · 6y ago · 0 comments
The endpoint returning the string of "Looks like you're based in Netherlands" is a nodej.js script that has this defined in the top:
const MESSAGE = "Hey - it looks like you're based in $countryName."
Sometime later in the code, in a function I manipulate this string in the module's export function: module.exports.getDiscountData = function(countryCode, countyName, etc) {
// Fetch the right message
let message = counryValues[countryCode]; // We get MESSAGE
message = MESSAGE.replace("$countryName", countryName) // oops - we overwrote MESSAGE with a new value!
message = MESSAGE.replace("$otherVariable", etc)
return message;
}And for each country, I have keys /values listed, like: "GB": MESSAGE, "NL": MESSAGE, "HU": MESSAGE_2
The problem was that once the first request replaced the country name, MESSAGE was mutated, and it now had the value "Hey - it looks like you're based in Netherlands." instead of "Hey - it looks like you're based in $countryName."
I had no idea this would happen. And that a "const" in Javascript is a mutable thing. I fixed it by deep copying the string of the original message.
The super interesting part is that I did not notice this problem, as when I was testing, I did low frequency testing. As I am using Lambda, I probably got a new container created, where MESSAGE was re-initialized. But with the HN traffic, the containers stayed alive longer, making this mutated string issue a problem.
By JS strings are immutable, and String.prototype.replace doesn't modify in place, it returns a fresh string. So, this shouldn't be possible as described.