Sohan's Blog

Things I'm Learning

Hardcoded URLs in Javascript Are Too Slippery

Photo credits to Esteban Cavrico

I was working on a web project that lets you delete some records using Ajax. The following is just an example, but you might be familiar with a similar code already:

This code used to work when the DELETE endpoint was indeed under ‘/blog/posts’. However, at some point a developer wants to remove the ‘/blog’ from all the endpoints to put them directly under ‘/posts’! You can see, in such cases it is very hard to catch the bug that would be caused by the faulty JS code.

Here’s a quick recommendation:
Don’t hardcode the URLs (or anything that is actually a server configuration) inside your JS. 
This is a code smell, as its duplicating code. But its also dangerous, because its hard to catch/fix these defects since they can be buried deep under an untested Javascript file. Instead feed this data from your server side code and you’ll mitigate risk that way.