Here's my approach:
First step, create a .env file in the root directory of your function, in the same directory where package.json is located (and your function's .js file). For this example, my .env file contains one variable as follows:
SQL_SERVER_DB="TestDB"
Next step, in your package.json file, add the dotenv dependency (i've used the latest version as of this answer):
"dependencies": {
"dotenv": "^16.0.3"
}
In your lambda function, figure out if you're running locally or not:
// see if we're running local or in aws lambda
const isLocal = process.env.AWS_SAM_LOCAL === 'true';
// configure sqlConfig with environment vars
let sqlConfig = {
database: ''
// ... etc
}
I added this variable as a global to the beginning of the file, before the main lambda function definition.
At the beginning of my lambda function, I call:
loadEnvironmentVars();
which is defined as:
Note: I defined sqlConfig as a global object before I call this function. That's because this object will be updated with environment variables.
function loadEnvironmentVars () {
console.log("load environment vars, isLocal: " + isLocal);
if (isLocal) {
// read the env variables from the .env file and parse them
// note: env vars are set differently when running in lambda
try {
dotenv.config();
// Read and parse the .env file
const envBuffer = fs.readFileSync('.env');
const envConfig = dotenv.parse(envBuffer);
// Load the environment variables into process.env
for (const key in envConfig) {
process.env[key] = envConfig[key];
console.log("env variable found: " + key + "=" + process.env[key]);
}
} catch (err) {
console.log("Failed to load local .env variables: " + err.message);
}
}
// set your environment vars used in this lambda function here:
// note: sqlConfig is a global object!
sqlConfig.database = process.env.SQL_SERVER_DB ? process.env.SQL_SERVER_DB : '';
}
When running locally, after loadEnvironmentVars() is called, the sqlConfig.database property should be set to "TestDB".
When Running In AWS Lambda (Production)
You will also need to set your environment variables in AWS Lambda in order for your code to work in both development and in production. You can learn how to do this here:
https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
Source Control
Make sure your local .env file is not included in your source control repository.