Nokto

n8n environment variables: how to add, read and secure them

By Abdellah El KharrazePublished 6 min read

In short

On self-hosted n8n, you add an environment variable to the container (docker run's -e option, the environment section in docker compose, or a .env file), then restart. In a workflow, you read it with {{ $env.VARIABLE_NAME }}. Since n8n 2.0, that access is blocked by default in nodes (N8N_BLOCK_ENV_ACCESS_IN_NODE=true): re-allow it explicitly, or better, store secrets in credentials.

Key takeaways

  • Environment variables configure the n8n instance; they are set at the container or system level, not in the editor.
  • In a workflow, $env.NAME reads a variable, if access is not blocked.
  • The “access to env vars denied” error comes from N8N_BLOCK_ENV_ACCESS_IN_NODE, set to true by default since n8n 2.0.
  • For a secret (API key, password), use n8n credentials, which are encrypted, rather than a variable every workflow can read.

Environment variables are how you configure a self-hosted n8n instance: database, public URL, time zone, history retention, security. They are also sometimes used to pass values to workflows. Since n8n 2.0, that second use has changed, and the “access to env vars denied” error has become one of the most asked questions. This guide covers everything: adding a variable, reading it, securing it, and the variables you need to know.

Two uses not to confuse

  • Configuring the instance: DB_TYPE, WEBHOOK_URL, GENERIC_TIMEZONE… n8n reads these variables at startup. They only apply to self-hosting: on n8n Cloud, configuration is managed by n8n.
  • Passing a value to a workflow: an API URL, an environment identifier (“production” or “staging”), a shared parameter. You read it with $env. This is the use n8n 2.0 restricted.

Adding an environment variable

With docker run

docker run -d --name n8n -p 5678:5678 \
  -e GENERIC_TIMEZONE=America/Chicago \
  -e TZ=America/Chicago \
  -e API_CRM_URL=https://crm.example.com/api \
  -v n8n_data:/home/node/.n8n \
  docker.n8n.io/n8nio/n8n

To change a variable, you have to remove and recreate the container with the new value; the volumes keep your data.

With docker compose

services:
  n8n:
    image: docker.n8n.io/n8nio/n8n:<version>
    environment:
      GENERIC_TIMEZONE: America/Chicago
      TZ: America/Chicago
      API_CRM_URL: https://crm.example.com/api
      N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY}   # read from the .env file
      EXECUTIONS_DATA_PRUNE: "true"               # quote booleans

After a change: docker compose up -d. Compose recreates the container if its configuration changed. A docker compose restart alone does not reread the file.

With a .env file

The .env file next to the compose file provides the values for ${...} expressions. It is the place for the instance's secrets (database password, encryption key), as long as you never commit it and restrict who can read it.

With secret files

Most n8n variables accept a _FILE-suffixed variant that reads the value from a file, handy with Docker or Kubernetes secrets: DB_POSTGRESDB_PASSWORD_FILE=/run/secrets/db_password.

npm install or system service

Without Docker, export the variables in the process environment before starting n8n (export NAME=value), or declare them in the systemd service file (Environment=NAME=value) and reload the service.

In queue mode

Variables must be set on every process: main instance, workers and webhook processes. A variable present on the main instance but missing on the workers gives you a workflow that works in a manual test and fails in production.

Reading a variable in a workflow

In any field in expression mode:

{{ $env.API_CRM_URL }}/contacts

In the Code node (JavaScript):

const base = $env.API_CRM_URL;
return [{ json: { url: `${base}/contacts` } }];

process.env is not the right way in the Code node: since n8n 2.0, code runs in an isolated task runner that does not expose the instance's environment. Use $env, or better, pass the value as an input to the node.

The “access to env vars denied” error

This is the question that comes up most since the 2.0 update. It means the instance forbids nodes from reading environment variables. That is intentional: to improve security, n8n 2.0 set N8N_BLOCK_ENV_ACCESS_IN_NODE to true by default. A workflow (or an editor user) can therefore no longer read the encryption key, the database password or any other secret in the server's environment.

Fix 1 (recommended): use credentials

If the value is a secret (API key, token, password), create a credential in n8n. Credentials are encrypted with the instance key, shared only with authorized people, and usable by nodes without ever appearing in execution data. For an API without a dedicated node, the HTTP Request node's generic “Header Auth” or “Bearer Auth” credential does the job.

Fix 2: re-allow access, knowingly

environment:
  N8N_BLOCK_ENV_ACCESS_IN_NODE: "false"

Recreate the container. With task runners in external mode, the runners container has its own environment: check that the variable you read is available there too, according to the task runner documentation for your version. Keep in mind that every workflow, and therefore every user who can create one, will then be able to read the whole environment.

Fix 3: n8n Variables

For non-secret values shared between workflows (a URL, an account ID, an environment flag), n8n Variables, managed in the interface and read with $vars.NAME, are cleaner than the server environment. Their availability depends on your plan.

Variables to know for production

Deployment and URLs

VariableExampleRole
N8N_HOSTn8n.example.comInstance hostname
N8N_PORT5678Listening port (5678 by default)
N8N_PROTOCOLhttpsPublic protocol
WEBHOOK_URLhttps://n8n.example.com/Public webhook URL, essential behind a proxy
N8N_PROXY_HOPS1Number of proxies in front of n8n
N8N_EDITOR_BASE_URLhttps://n8n.example.com/Public editor URL (links in emails)

Security

VariableDefaultRole
N8N_ENCRYPTION_KEYGenerated on first startEncrypts credentials. Set it and back it up.
N8N_BLOCK_ENV_ACCESS_IN_NODEtrue since 2.0Blocks $env in nodes
N8N_SECURE_COOKIEtrueSession cookie restricted to HTTPS
N8N_PUBLIC_API_DISABLEDfalseDisables the public API (and therefore any API-based monitoring)

Database

VariableExample
DB_TYPEpostgresdb
DB_POSTGRESDB_HOST, _PORT, _DATABASEpostgres, 5432, n8n
DB_POSTGRESDB_USER, _PASSWORD (or _PASSWORD_FILE)n8n, secret

Executions and history

VariableDefaultAdvice
EXECUTIONS_DATA_SAVE_ON_SUCCESSallKeep all: without saved successes, you cannot detect a stopped workflow through the API
EXECUTIONS_DATA_SAVE_ON_ERRORallKeep all
EXECUTIONS_DATA_PRUNEtrueAutomatic history pruning
EXECUTIONS_DATA_MAX_AGE336 (hours)Three to four weeks to analyze rhythms
EXECUTIONS_DATA_PRUNE_MAX_COUNT10000Raise it if you have many executions
EXECUTIONS_TIMEOUT-1 (none)Set a limit to avoid never-ending executions
EXECUTIONS_MODEregularqueue for queue mode

Time zone, logs, metrics

VariableExampleRole
GENERIC_TIMEZONEAmerica/Chicago, Europe/LondonTime zone for schedules and $now
TZAmerica/Chicago, Europe/LondonSystem time zone inside the container
N8N_LOG_LEVELinfodebug to diagnose, temporarily
N8N_METRICSfalsetrue to expose /metrics (keep it internal)
QUEUE_HEALTH_CHECK_ACTIVEfalsetrue to probe workers in queue mode
N8N_DEFAULT_BINARY_DATA_MODEdefaultfilesystem to keep files out of the database

n8n's official documentation contains the full list, organized by area, with each version's defaults.

Common mistakes

  • Changing N8N_ENCRYPTION_KEY on an existing instance: every credential becomes unreadable.
  • Forgetting WEBHOOK_URL behind a proxy: webhooks show localhost:5678 and receive nothing.
  • Forgetting GENERIC_TIMEZONE: the “every day at 8 AM” schedule fires at the wrong hour, since n8n defaults to America/New_York.
  • Turning off saving of successes to save space: silence monitoring becomes impossible.
  • Putting secrets in the environment and re-allowing $env: any user who creates a workflow can read them.

What about monitoring?

Three variables directly determine whether you can monitor your instance: EXECUTIONS_DATA_SAVE_ON_SUCCESS (without saved successes, a stopped workflow looks like a running one), EXECUTIONS_DATA_MAX_AGE (enough history to learn rhythms) and N8N_PUBLIC_API_DISABLED (the public API must stay on for an external tool like Nokto to read your workflows). Check them before setting up monitoring, and read our guide to monitoring n8n in production.

Frequently asked questions

How do I add an environment variable to n8n with Docker?

With docker run, add -e NAME=value to the command. With docker compose, add the line NAME: value to the n8n service's environment section (or to a referenced .env file), then run docker compose up -d to recreate the container. A simple restart does not always reread a modified compose file.

How do I use an environment variable in an n8n workflow?

In an expression, write {{ $env.VARIABLE_NAME }}. In the Code node, $env.VARIABLE_NAME. This only works if access to environment variables from nodes is not blocked by N8N_BLOCK_ENV_ACCESS_IN_NODE.

What does the “access to env vars denied” error mean in n8n?

That the instance forbids nodes from reading environment variables, which is the default since n8n 2.0. To allow it, set N8N_BLOCK_ENV_ACCESS_IN_NODE=false and recreate the container; with external task runners, also check the runners container's environment. The best fix is still to pass secrets through credentials.

What is the difference between environment variables and n8n Variables ($vars)?

Environment variables configure the instance and are set on the server. n8n Variables ($vars) are values shared between workflows, managed in the interface, available depending on the plan. Neither is meant to store secrets: that is what credentials are for.

Why isn't my environment variable taken into account?

Most often: the container was not recreated after the change, the variable is set on a service other than n8n (or not on the workers in queue mode), a boolean value is not quoted in the YAML, or access from nodes is blocked.

Sources

Try Nokto for free