Skwal
Skwal

Reputation: 2160

socket.io hardcoded vs dynamic connection url

Why most tutorials, examples and questions here use the local IP or localhost (or any other hard-coded path) like this:

var socket = io.connect('http://127.0.0.1:3700');

Instead of simply:

var socket = io.connect(document.location.protocol+'//'+document.location.host);

Or even:

var socket = io.connect();

Are there any risks making it dynamic like this? Are there any better way to make my script work locally and in production without having to change this value every time?

Upvotes: 3

Views: 1890

Answers (1)

1nsane
1nsane

Reputation: 1047

I don't see any risks involved, if you have a dynamic connection url instead of a hard-coded one.

In my opinion a hard-coded url like in your first example is more easier for beginners to understand. The second example could be confusing. (Actually I also had to check, if document.location.host contains the port number or not). And that's why most examples and tutorials use the hard-coded variant, I guess.

If the third example works in both your development and production environment, you should use it. But in cases where the socket is running on a different port and/or host than the rest of the application, it does not work and it is necessary to hard-code it somewhere in the script.

Upvotes: 3

Related Questions