Netlify functions are AWS’s serverless lambda functions that allow you to define your business logic and functions as an API and expose them with an endpoint.
But some of us developers need environments for the sake of development and deployment. The Netlify functions only take environment variables from the UI dashboard. We can’t use the environment variables for branch deploys.
I have found a workaround for this by using a JSON file and replacing the JSON values using a node function. This can be achieved in 4 easy steps:
- Create env JSON files & varibales.json file
- Create a node function to manipulate variables.json
- Import values from variables.json for use
- Add the scripts to package.json
Step-1: Create env JSON files & varibales.json file
env folder and create JSON files based on environments like
variables.json outside the env folder (which is used for the netlify functions).
Step-2: Create a node function to manipulate variables.json
envChange.js file to manipulate the varibales.json file with the below code.
This file effectively copies the values from the JSON files under
env folder and pastes to the
variables.json file based on the arguments.
This command will replace all the data in
varables.json with the values from
node envChange --env=dev
Likewise, when we use
—-env=production it will replace the code from
Step-3: Import values from variables.json for use
Now use the variables from
variables.json file. This will give you the exact environment variables needed for your branch deployment.
Step-4: Add the scripts to package.json
We can also add this to the
package.json file like below
"build:dev" : "node envChange --env=dev",
"build:testing": "node envChange --env=testing",
"build:production": "node envChange --env=production"
Horray! We have implemented a custom business logic using netlify functions with multiple environmets.