Set dynamic Env Variable in Preview

We have a backend that has this preview url structure:

.abc.def.com

We want to dynamically pull the COMMIT HASH for each preview deployment and inject it into the application.

All our attempts failed so far.

We tried:

//apps/store/scripts/expand-env.js

const dotenv = require("dotenv")
const dotenvExpand = require("dotenv-expand")

const myEnv = dotenv.config({ path: ".env.local" })
dotenvExpand.expand(myEnv)

and let this run in our build command:

"build": "node scripts/expand-env.js && printenv && next build",

But this does not overwrite the dynamic variables we have:

BACKEND_URL=${COMMIT_HASH}.abc.def.com

We simply dont understand why this is so hard to do or what is wrong here?

Thanks for any help

Have you tried using NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA ?

If you want to expand or add env variable I recommend using the env key in next.config. You can pull the data in from your .env file and expand the variables you need

2 Likes