/n8n-tutorials

How to set environment variables in n8n?

Learn how to set and manage environment variables in n8n using the UI, .env files, command line, or Docker to securely store sensitive data and customize workflows.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to set environment variables in n8n?

To set environment variables in n8n, you can use the n8n UI interface, command line arguments, environment files (.env), or Docker environment variables. Environment variables allow you to securely store sensitive information like API keys and customize your n8n instance's behavior without hardcoding values in your workflows.

 

Step 1: Understanding Environment Variables in n8n

 

Environment variables in n8n are system-level settings that control various aspects of the application's behavior. They can be used to:

  • Configure database connections
  • Set up security features
  • Define execution environments
  • Store sensitive credentials
  • Control workflow execution settings

n8n supports different types of environment variables:

  • System environment variables: Control n8n's core functionality
  • Custom environment variables: Store your own values for workflow use

 

Step 2: Setting Environment Variables via the n8n UI

 

The simplest way to set environment variables in n8n is through the user interface:

  • Login to your n8n instance as an admin user
  • Navigate to Settings → Environment Variables
  • Click "Add Environment Variable"
  • Enter the variable key and value
  • Save your changes

Here's the detailed process:

  1. Open your n8n instance in a browser
  2. Log in with admin credentials
  3. Click on the Settings icon in the sidebar (gear icon)
  4. Select "Environment Variables" from the menu
  5. Click the "Add Environment Variable" button
  6. Enter a name for your variable (e.g., "API_KEY")
  7. Enter the value for your variable
  8. Click "Save" to store the variable

These variables will be available to use in your workflows.

 

Step 3: Using Environment Variables in Workflows

 

Once you've set environment variables, you can use them in your workflows:

  1. Open or create a workflow
  2. Add a node that requires configuration
  3. In any field, you can reference an environment variable using the following syntax:
{{$env.YOUR_VARIABLE_NAME}}

For example, if you set an environment variable called API_KEY, you would reference it as:

{{$env.API\_KEY}}

This approach keeps sensitive information out of your workflow configurations.

 

Step 4: Setting Environment Variables via .env File

 

For persistent configuration, you can use a .env file:

  1. Create a new file named .env in your n8n root directory
  2. Add your environment variables in KEY=VALUE format
  3. Save the file
  4. Restart n8n to apply the changes

Example .env file:


# Database configuration
DB\_TYPE=postgresdb
DB_POSTGRESDB_HOST=localhost
DB_POSTGRESDB_PORT=5432
DB_POSTGRESDB_DATABASE=n8n
DB_POSTGRESDB_USER=postgres
DB_POSTGRESDB_PASSWORD=password

# n8n configuration
N8N\_PORT=5678
N8N\_PROTOCOL=http
N8N\_HOST=localhost
N8N\_PATH=/

# Custom environment variables
API\_KEY=your-api-key-here
MY_CUSTOM_URL=https://example.com

This method is especially useful for self-hosted n8n instances.

 

Step 5: Setting Environment Variables via Command Line

 

When starting n8n from the command line, you can set environment variables directly:

For Linux/Mac:


export N8N\_PORT=5678
export API\_KEY=your-api-key-here
n8n start

For Windows (Command Prompt):


set N8N\_PORT=5678
set API\_KEY=your-api-key-here
n8n start

For Windows (PowerShell):


$env:N8N\_PORT = "5678"
$env:API\_KEY = "your-api-key-here"
n8n start

 

Step 6: Setting Environment Variables with Docker

 

If you're running n8n in Docker, you can set environment variables in your Docker run command or docker-compose file:

Using docker run:


docker run -it --rm \\
  --name n8n \\
  -p 5678:5678 \\
  -e N8N\_PORT=5678 \\
  -e API\_KEY=your-api-key-here \\
  -e DB\_TYPE=postgresdb \\
  -e DB_POSTGRESDB_DATABASE=n8n \\
  -e DB_POSTGRESDB_HOST=postgres \\
  -e DB_POSTGRESDB_PORT=5432 \\
  -e DB_POSTGRESDB_USER=postgres \\
  -e DB_POSTGRESDB_PASSWORD=password \\
  n8nio/n8n

Using docker-compose.yml:


version: '3'

services:
  n8n:
    image: n8nio/n8n
    ports:
    - "5678:5678"
    environment:
    - N8N\_PORT=5678
    - API\_KEY=your-api-key-here
    - DB\_TYPE=postgresdb
    - DB_POSTGRESDB_DATABASE=n8n
    - DB_POSTGRESDB_HOST=postgres
    - DB_POSTGRESDB_PORT=5432
    - DB_POSTGRESDB_USER=postgres
    - DB_POSTGRESDB_PASSWORD=password
    volumes:
    - n8n\_data:/home/node/.n8n

volumes:
  n8n\_data:

 

Step 7: Managing Encrypted Environment Variables

 

For enhanced security, n8n allows you to encrypt sensitive environment variables:

  1. Set up an encryption key by setting the N8N_ENCRYPTION_KEY environment variable
  2. Any environment variables added through the UI will be automatically encrypted
  3. To encrypt variables in your .env file, prefix them with N8N_ENCRYPTION_KEY=

Example:


N8N_ENCRYPTION_KEY=your-strong-encryption-key

Once the encryption key is set, variables stored through the UI will be encrypted in the database.

 

Step 8: Common System Environment Variables

 

Here are some important system environment variables you might want to configure:

  • N8N\_PORT: Port on which n8n will listen (default: 5678)
  • N8N\_HOST: Host name n8n runs on
  • N8N\_PROTOCOL: Protocol to use (http or https)
  • N8N\_PATH: Base path for n8n
  • N8N_ENCRYPTION_KEY: Key for encrypting credentials
  • N8N_USER_FOLDER: Path to store user data
  • DB\_TYPE: Database type (sqlite, postgresdb, mysqldb, etc.)
  • WEBHOOK\_URL: Public URL for webhook endpoints
  • EXECUTIONS\_PROCESS: Define how workflows are executed (main or own)
  • GENERIC_TIMEZONE: Default timezone for n8n (e.g., America/New_York)

 

Step 9: Using Environment Variables in Function Nodes

 

In Function nodes, you can access environment variables using the $env object:


// Example code in a Function node
const apiKey = $env.API\_KEY;
const baseUrl = $env.BASE\_URL;

// Use the variables in your code
const response = await fetch(`${baseUrl}/api/data`, {
  headers: {
    'Authorization': `Bearer ${apiKey}`
  }
});

return response.json();

This allows you to keep sensitive data out of your workflow code.

 

Step 10: Troubleshooting Environment Variables

 

If you're having issues with environment variables:

  • Verify the variable is correctly set in your chosen method (UI, .env, command line, Docker)
  • Check for typos in variable names (they're case-sensitive)
  • Ensure n8n was restarted after setting variables (if not using the UI method)
  • Confirm proper syntax when referencing variables in workflows ({{$env.VARIABLE\_NAME}})
  • Check the logs for any error messages related to environment variables

For debugging, you can create a simple workflow with a Function node to print out environment variables:


// Debug environment variables
return {
  data: {
    availableEnvVars: $env
  }
};

This will show all available environment variables in your execution results.

 

Step 11: Environment Variables Best Practices

 

Follow these best practices when working with environment variables in n8n:

  • Use uppercase names with underscores for environment variables (e.g., API_KEY, DATABASE_URL)
  • Never commit .env files to source control (add them to .gitignore)
  • Use the encryption key feature for sensitive variables
  • Document your environment variables for team reference
  • Use different variables for development, staging, and production environments
  • Regularly rotate sensitive keys and update the corresponding environment variables
  • Limit access to environment variable settings to administrators only

 

Step 12: Environment Variables in CI/CD Pipelines

 

When automating n8n deployment with CI/CD:

  1. Store sensitive environment variables in your CI/CD platform's secrets manager
  2. Generate the .env file during deployment or pass variables to Docker
  3. Consider using environment-specific variable sets
  4. Validate environment variable presence before deployment

Example GitHub Actions workflow:


name: Deploy n8n

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
      
    - name: Generate .env file
        run: |
          echo "N8N\_PORT=5678" >> .env
          echo "N8N\_PROTOCOL=https" >> .env
          echo "N8N_HOST=${{ secrets.N8N_HOST }}" >> .env
          echo "N8N_ENCRYPTION_KEY=${{ secrets.N8N_ENCRYPTION_KEY }}" >> .env
          echo "DB\_TYPE=postgresdb" >> .env
          echo "DB_POSTGRESDB_HOST=${{ secrets.DB\_HOST }}" >> .env
          echo "DB_POSTGRESDB_DATABASE=n8n" >> .env
          echo "DB_POSTGRESDB_USER=${{ secrets.DB\_USER }}" >> .env
          echo "DB_POSTGRESDB_PASSWORD=${{ secrets.DB\_PASSWORD }}" >> .env
          echo "API_KEY=${{ secrets.API_KEY }}" >> .env
      
    - name: Deploy to server
        # Your deployment steps here

This approach keeps sensitive data secure while automating deployments.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022