Gatsby: How to get window.location.protocol and window.location.host?

Created on 28 Aug 2018  Â·  3Comments  Â·  Source: gatsbyjs/gatsby

Summary

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?

Most helpful comment

@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

All 3 comments

On this page of the documentation about Debugging HTML Builds, it says:

  1. Some of your code references “browser globals” like window or document. If this is your problem you should see an error above like “window is not defined”. To fix this, find the offending code and either a) check before calling the code if window is defined so the code doesn’t run while gatsby is building (see code sample below) or b) if the code is in the render function of a React.js component, move that code into “componentDidMount” which ensures the code doesn’t run unless it’s in the browser.

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
Was this page helpful?
0 / 5 - 0 ratings

Related issues

totsteps picture totsteps  Â·  3Comments

ferMartz picture ferMartz  Â·  3Comments

kalinchernev picture kalinchernev  Â·  3Comments

signalwerk picture signalwerk  Â·  3Comments

brandonmp picture brandonmp  Â·  3Comments