Reading credentials from .env file

I was trying to pass credentials data from the .env file to the n8n server. I am using Docker Compose. Here is my YAML file :

services:
  n8n:
    image: n8nio/n8n:latest
    restart: always
    ports:
      - "5678:5678"
    env_file:
      - .env
    # environment:
    #   - FIREBASE_SERVICE_ACCOUNT_EMAIL=${FIREBASE_SERVICE_ACCOUNT_EMAIL}
    #   - FIREBASE_REGION=${FIREBASE_REGION}
    #   - FIREBASE_PRIVATE_KEY=${FIREBASE_PRIVATE_KEY}
    #   - OPENAI_API_KEY=${OPENAI_API_KEY}
    volumes:
      - n8n_data:/home/node/.n8n
      - ./local-files:/files

volumes:
  n8n_data:

And here is my .env file:

N8N_BLOCK_ENV_ACCESS_IN_NODE=false
N8N_BLOCK_FILE_ACCESS_TO_N8N_FILES=false
N8N_PORT=5678
N8N_HOST=localhost
N8N_PROTOCOL=http
WEBHOOK_URL=http://localhost:5678/
GENERIC_TIMEZONE=Asia/Tokyo
TZ=Asia/Tokyo
NODE_ENV=production
N8N_ENCRYPTION_KEY=testkey


# Firebase
[email protected]
FIREBASE_REGION=asia-northeast1
FIREBASE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nXXX==\n-----END PRIVATE KEY-----\n

# OpenAI
OPENAI_API_KEY=sk-xxxxx

N8N_ALLOW_ENV_VARIABLES=true

N8N_ALLOW_ENV_VARIABLES=true is already there. I can see the variables are loaded when I enter Printenv in the console of the Docker volume.

However, either “$env” or “process.env” always returns an error or is empty, no matter whether from a code node or from the expression field.

I’ve been stuck for a few days. I’ve tried to ask different LLMs, find info from docs, and search for questions from others. I still don’t get it

Information on your n8n setup

  • n8n version: latest
  • Database (default: SQLite): firebase
  • n8n EXECUTIONS_PROCESS setting (default: own, main): default
  • Running n8n via (Docker, npm, n8n cloud, desktop app): docker compose
  • Operating system: WLS on Windows

Hello @WesleyWai

From my attempts, $env always appears empty unless you reference a specific variable like {{ $env.N8N_HOST }}, Even if it shows undefined in the preview, you’ll get the correct value once the node executes.

As for process.env, it actually outputs all environment variables when the node runs, even though it may look empty in the preview.

Note: I use the environment: section in my Docker Compose file, I haven’t tried using env_file: yet..

2 Likes

Thanks @mohamed3nan.

It works, and probably it has always worked.

1 Like

Hey @WesleyWai great to know that it works! if @mohamed3nan reply solved the problem, please mark the reply as answered so people know what to do in such case, thank you!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.