Multiple environments in Netlify functions
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
Create a env
folder and create JSON files based on environments like dev.json
, testing.json
, production.json
.
Now create variables.json
outside the env folder (which is used for the netlify functions).
Step-2: Create a node function to manipulate variables.json
Now create 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 env/dev.json
node envChange --env=dev
Likewise, when we use —-env=testing
and —-env=production
it will replace the code from env/testing.json
and env/produciton.json
into variables.json
respectively.
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
"scripts": {
"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.
Say Hi, It’s free at @matheswaaran_S or https://matheswaaran.com