Hi, @PabloRomanH. This is a copy of my reply to the support ticket (with some minor edits):
Thank you for asking about this. We do cover the missing read-only environment variables in the Functions documentation here:
Quoting that page:
The following read-only environment variables are available to serverless functions (including scheduled functions, background functions, and On-demand Builders):
-
NETLIFY_IMAGES_CDN_DOMAIN
: if image compression post processing is enabled, the base URL used for all processed images; for example, d33wubrfki0l68.cloudfront.net
.
-
SITE_NAME
: name of the site, its Netlify subdomain; for example, petsof
.
-
SITE_ID
: unique ID for the site; for example, 1d01c0c0-4554-4747-93b8-34ce3448ab95
.
-
URL
: URL representing the main address to your site. It can be either a Netlify subdomain or your own custom domain if you set one; for example, https://petsof.netlify.app
orhttps://www.petsofnetlify.com
.
Also available are the runtime environment variables provided by AWS.
Note that other Netlify read-only environment variables are available when you use Netlify Dev to help with local development, but only the above subset are available in all other environments.
So, in the Functions documentation, we are clear that only a subset of the read-only build environment variables are available to the deployed Function. As COMMIT_REF
is one of the read-only build environment variables and not listed above, it will not be available to Functions.
There is a workaround for this which is a bit “old school”. It is to have placeholder string the in function file and then to do a find/replace during the build. You can do this in the build command itself (in the node code). Also, as the build image is Linux, you can use the time-tested Unix workhorse command sed
as shown below. In this hypothetical example, I’m making the following assumptions:
- the function file is found at this path relative to the base directory:
functions/function-name.js
- the file above contains a definition like so:
const COMMIT_REF = "COMMIT_REF_PLACEHOLDER";
- build command is:
npm run build
You could then hard-code the commit ref during the build by adding the following before the build commands:
sed -i s/COMMIT_REF_PLACEHOLDER/${COMMIT_REF}/g functions/function-name.js && npm run build
This will cause sed
to replace the literal string COMMIT_REF_PLACEHOLDER
with the value of build environment variable COMMIT_REF
. Then, only if the sed
command finishes with no error, run the build command. If there is an error with the sed
command the build will immediately exit with an error. Note, it still won’t be available via process.env
with that workaround. However, you can work with it as a constant (or variable if you prefer) using the workaround above.
If this workaround doesn’t work for you or if there are other questions, please let us know.