Skip to main content

Environment Variables

Scaffoldly uses dotenv and dotenv-expand to manage environment variables in your application. This allows you to define environment variables in a .env file and access them in your code seamlessly.

Creating .env Files

warning

Do not add secrets or sensitive information directly into .env files, instead use Secrets for sensitive data.

tip

Since Scaffoldly can manage secrets, we recommend checking your .env files into Source Control. This allows you to easily manage and share your environment variables across your team.

To create a .env file, simply create a new file named .env in the root of your project and add your environment variables in the following format:

# .env
DATABASE_URL="your-database-url"

Branch-Specific .env Files

If you want to have different environment variables for different branches, you can create branch-specific .env files. For example:

  • use .env and/or .env.main file for your main branch,
  • a .env.staging file for your staging branch, overriding any variables defined in .env,
  • a .env.production file for your development branch, overriding any variables defined in .env.

You can see which .env files are used when deploying, and the order of precedence:

npx scaffoldly deploy --dryrun
Example Output

Here's an example output of the deployment process:

🚀 Deployment Complete!
...
📄 Env Files: .env.main, .env
...

Accessing Environment Variables in Your Code

You can access the environment variables in your code using process.env. For example:

const dbUrl = process.env.DATABASE_URL;

dotenv-expand Usage

If you need to reference system-level environment variables within your .env file, you can use dotenv-expand. For example:

.env file
# .env
DATABASE_URL="postgres://root:testing@localhost:5432/mydb"
GitHub Actions Override
# .github/workflows/scaffoldly.yml
env:
DB_HOST: 'mydbinstance.abcdefghij.us-east-1.rds.amazonaws.com:5432'
.env.staging file
# .env.staging
DATABASE_URL="postgres://${DB_HOST}/mydb"

A Real-World Example

Let's build out secrets and environment variables for a real-world application that connects to a PostgreSQL database and uses SendGrid for sending emails.

Your application needs:

  • A database URL
    • Developers use postgresql://root:testing@localhost:5432/mydb locally
    • A different Database URL for use in production
  • An API key for SendGrid
    • Developers get this value from 1Password for their local environment
    • A different API key for use in production

Set up your project, and GitHub Actions in the following way:

.profile
export SENDGRID_API_KEY_DEV="some_shared_sendgrid_api_key" # copied from 1Password

Explanation:

  • Since SENDGRID_API_KEY is sensitive, it should not be stored in your codebase.
  • dotenv will pull it into .env at runtime.

Questions, Feedback, and Help