This has been insanely complicated and time consuming but I will share the solution I’ve reached for now. For me I have 4 lambda functions each in their own folders that need to make use of the CONTEXT to switch between prod and dev api endpoints - fairly standard use case.
Attempting to use sed to replace CONTEXT with $CONTEXT technically works but it’s messy, when running the script locally I end up with git changes that I need to handle. Also, of course, the linter complains about the constant condition and you have to comment everywhere why this weird string is there so really not a fan of that.
So I looked for better options. One simple approach I tried was using
dotenv. In my prebuild script I run
printenv > .env to put everything in a file that dotenv can pick up (obviously I could just put the stuff I need but I was trying to keep things simple!). Unfortunately this doesn’t work due to dotenv failing to find the .env file. I guess this is down to zip it and ship it ignoring it as it’s not explicitly imported?
So what I’m doing now is writing the build env vars to a json file in my
prebuild script with:
python -c 'import json, os;print(json.dumps(dict(os.environ)))' > env.json
Then in my lambdas I can import them with
const env = require('./env.json');
Finally I can use
env.CONTEXT === 'production' to switch the api tokens I use per environment.
Please sort this out Netlify, it’s really at odds with how effortless and straightforward everything else is when using the service