Detect localhost, staging or production and access env vars in liquid

Detect localhost, staging or production and access env vars in liquid

simonbarker
Shopify Partner
8 0 8

Hi,

 

I've got two stores, one is a dev store and the other is out production store. I develop our theme locally and deploy to the dev store periodically. When we are ready to launch we then apply the theme to the production store. 

 

We make requests to different end points depending on which environment the store is running in (local, dev store, prod store) and want to be able to pass these in as environment variables, or at least detect in liquid which environment we are running in.

 

I can't quite work out who to do it. Passing the `--environment` flag to `shopify theme dev` doesn't seem to do anything, and even if it did I can't figure out how to access the shopify.theme.toml variables in liquid anyway.

 

The closest I can get is to check the request.canonical_url or request.host value but that doesn't work for local dev.

 

Any help would be great

 

Thanks

 

Simon 

Reply 1 (1)

diegovogel
Shopify Partner
16 0 4

I'm trying to do the same thing. The closest I've gotten is conditionally defining a global JS variable.

 

In the site <head>, do something like this:

 

<script>
    if (window.location.hostname === '127.0.0.1') {
        window.dataApiBaseUrl = 'http://local-domain-here/api/v3';
    } else {
        window.dataApiBaseUrl = 'https://production-domain-here/api/v3';
    }
</script>

 

 

Then you can reference dataApiBaseUrl anywhere else (script tags or JS files included on the page). This is also handy for exposing theme settings to JS.

 

But I wish there was a way to do this with Liquid so we could do things like load different versions of third-party scripts:

 

{% if environment == 'development' %}
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
{% else %}
  <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
{% endif %}

 

 

Sadly I haven't found a way to do that, so I may need to do it in our deploy script, which is kind of a pain.