Feature Request: Expose environment variables to JS/TS

In other projects where I am using Webpack I often access environment variables with process.env.SOME_API_KEY or process.env.NODE_ENV.

In Hugo I can do something similar with getenv "SOME_API_KEY". But this is not exposed to JavaScript/TypeScript files compiled with Hugo as far as I can tell. So instead I have resorted to this workaround:

{{ $key := getenv "SOME_API_KEY" }}
<script>window.SOME_API_KEY = '{{ $key }}'</script>

I am requesting that environment variables be exposed to ESBuild and accessible through process.env.

That probably won’t happen because it’s basically already built in. Have a look a the defines parameter:

defines [map]

Allow to define a set of string replacement to be performed when building. Should be a map where each key is to be replaced by its value.

{{ $defines := dict "process.env.NODE_ENV" `"development"` }}

JavaScript/TypeScript files compiled with Hugo

i assume you build your JS using js.Build.

then you can pass the ENV_KEY via params options on your js.Build.

{{ $api_key := getenv "SOME_API_KEY" }}
{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api_key" $api_key)) }}
<script type="text/javascript" src="{{ $js.RelPermalink }}" defer></script>

in your JS, you can access it:

import * as params from '@params';
2 Likes

Thanks, I switched over to this method.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.