I am defining a websocket connection in my .env and instead of hardcoding the path, I want it to be in a relative path. However, relative paths are not allowed in ws so I am building the full path of that web relative path websocket. In order for me to build the full url, i need to access window.location.protocol (so that I'll know whether to use 'ws://' or 'wss://') and window.location.host (which can be basically be localhost:8000 or myservername.com)
I can use window.location in gatsby develop but when I do gatsby build, it complains that 'window is not defined'
With that, how do I access window.location.protocol and window.location.host?
On this page of the documentation about Debugging HTML Builds, it says:
So, maybe you could try checking to make sure window is defined before using it? Hope that helps!
I usually do this whenever I need the window object:
const windowGlobal = typeof window !== 'undefined' && window
@franz-see @kinduff’s snippet is the best solution! Similarly, you could just do:
typeof window !== 'undefined' && window.location.protocol
and:
typeof window !== 'undefined' && window.location.host
Most helpful comment
@franz-see @kinduff’s snippet is the best solution! Similarly, you could just do:
and: