Trouble connecting to AWS RDS DB with Netlify Functions

Okay so I found the solution for my problem.

It seems I was wrong (Was most likely anyway).
Netlify is looking for the .env file in my repo and since (For obvious reasons) my .env is not public available.

Therefore MySQL connection returns undefined in all my process.env variables which my default will be localhost. That’s why it’s trying to connect to a local database and not my RDS.

Solution

Store your API_KEY in the Netlify build environment variables and build the .env using a script prior to running the build command.

scripts/create-env.js

// Using this to create env file based on Netlify UI Environments
const fs = require('fs')
fs.writeFileSync('./.env', `
DB_HOST=${process.env.DB_HOST}\n
DB_USER=${process.env.DB_USER}\n
DB_PASSWORD=${process.env.DB_PASSWORD}\n
DB_NAME=${process.env.DB_NAME}\n
`)

Run the script as part of your build

node ./scripts/create-env.js && <your_existing_webpack_build_command>

Solution from:

Thanks for trying to help @hrishikesh :slight_smile:

2 Likes