How to upload custom environment variables to Forest Admin Cloud

Hey guys,

I have some trouble using the forest admin cloud, I have a .env file with some variables:

CERTIFICATE_API_URL=https://example.com
CERTIFICATE_API_KEY=test@1234

When I call the pnpm forestadmin:build:package:publish I get an error because CERTIFICATE_API_URL and CERTIFICATE_API_KEY aren’t being uploaded somehow, I’m not sure the proper way to have .env file in forest admin cloud.

✖ Something went wrong: Forest Admin Cloud error: A valid CERTIFICATE_API_KEY must be provided.

Best regards,

1 Like

Hello @Salah_lachgar,

Thanks for your question.
Indeed as you mentionned, your .env file is not sent along with the code to your instance of Forest Cloud.
What you will have to do is replace the env variables in your code before sending it

The trick is to use the define function of esbuild.mjs, which is called during the build process.

/!\ warning: this will only replace strings, during the build process
so it will only work if you get your variables like that:
:green_circle: const CERTIFICATE_API_URL = process.env.CERTIFICATE_API_URL
and not if you use destructuring or some other means, like so:
:red_circle: const {CERTIFICATE_API_KEY} = process.env
so you may have to adapt either your code or the define function to work for your use case

for (const k in process.env) {
    define[`process.env.${k}`] = JSON.stringify(process.env[k])
}

await esbuild.build({
...
    entryPoints: ['./src/index.ts'],
    treeShaking: true,
    logLevel: 'debug',
    target: 'node18',
    platform: 'node',
    define,
})

from here.
Please let us know if this helps

2 Likes

Hey Nicolas,

Thank you so much for your solution, it did work although I needed to add a slight adjustment to the esbuild.mjs file so it can full work.

import "dotenv/config"; // I had to add this line to load the .env file
import * as esbuild from "esbuild";

const define = {}
for (const k in process.env) {
  define[`process.env.${k}`] = JSON.stringify(process.env[k])
}

await esbuild.build({
  entryPoints: ["./src/index.ts"],
  bundle: true,
  outdir: "dist/code-customizations",
  minify: true,
  treeShaking: true,
  logLevel: "debug",
  target: "node18",
  platform: "node",
  define,
});

I appreciate it again.

Best regards,

3 Likes