# Trouble connecting to AWS RDS DB with Netlify Functions

**URL:** <https://answers.netlify.com/t/trouble-connecting-to-aws-rds-db-with-netlify-functions/37620>\
**Category:** Support\
**Tags:** lambda-functions, deployment\
**Created:** [May 13, 2021, 12:57pm UTC](https://answers.netlify.com/t/trouble-connecting-to-aws-rds-db-with-netlify-functions/37620 "2021-05-13T12:57:09Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![AndreasL](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/andreasl/32/25367_2.png) [@AndreasL](https://answers.netlify.com/u/AndreasL)\
**Post date:** [May 13, 2021, 2:50pm UTC](https://answers.netlify.com/t/trouble-connecting-to-aws-rds-db-with-netlify-functions/37620/11 "2021-05-13T14:50:41Z")

</div>

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`

```auto
// 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:

> [@\[Support Guide\] Using environment variables on Netlify correctly](https://answers.netlify.com/t/support-guide-using-environment-variables-on-netlify-correctly/267/5):
>
> I answered using .env on Netlify to be able to use dotenv on your build on [SO](https://stackoverflow.com/a/48466680/2597114), but here is the cross post: WARNING: If this is a secret key, you will not want to expose this environment variable value in any bundle that gets returned to the client. It should only be used by your build scripts to be used to create your content during build. Issue dotenv-webpack expects there to be a .env file to load in your variables during the webpack build of your bundle. When the repository is checked out …

Thanks for trying to help @hrishikesh 🙂

---

_[View the full topic](https://answers.netlify.com/t/trouble-connecting-to-aws-rds-db-with-netlify-functions/37620)._
