Handling environment variables when Deploying a Static Site with NPM Scripts and Cloudflare Pages
I'm interested in designing and building scalable, reliable distributed systems.
Dynamic background spanning Software Engineering (Go, NestJS, ReactJS, Spring Boot) to DevOps (GitOps, Kubernetes, Ansible).
Experienced in CDN, Cloud: Ionos & AWS services: EC2, Lambda, S3, Amplify, ...
Open-source enthusiast, contribute to:
- Apache Traffic Control (https://github.com/apache/trafficcontrol/pulls?q=is%3Apr+author%3Antheanh201+)
- Apache Zeppelin (https://github.com/apache/zeppelin/pulls?q=is%3Apr+author%3Antheanh201+)
Problem
- When deploying a static site with NPM scripts that utilize bash commands and environment variables inside
package.jsonscripts, you might define something like:
"scripts": {
"transpile-js": ". .env; for file in "\${JS_FILES[@]}"; do(babel js/"\$file".js -o dist/js/"\$file".js --presets=@babel/preset-env); done"
}
However, when deploying with Cloudflare Pages, this approach can lead to errors such as:

Solution
Set the environment variables in the Cloudflare Pages dashboard.

Use dotenvx to preload environment variables instead of using the .env file, as Cloudflare doesn't support .env files.
"scripts": { "transpile-js": "dotenvx run -- bash -c 'read -r -a JS_FILES <<< "$JS_FILES"; for file in "${JS_FILES[@]}"; do(babel js/$file.js -o dist/js/$file.js --presets=@babel/preset-env); done'" }
For a complete example, you can check out the code: https://github.com/ntheanh201/cloudflare-static-site
Result
The error is gone and the deployment is successful.


