How to define custom environment variables available in the n8n workflow

Hello,

I’m searching a way to define variables that could vary through environments (dev, staging, prod°, …)

I don’t know how to do this, and didn’t see anything in the documentation or in the forum.

Maybe I’m not searching with the good words, but, is there a way to do this ?

My need would be to define a base URL, on my PC would be a “192.168.xx.xx”, but on a server, could be in a docker stack, so that could be a string like “api-server”.

This need could be extended to other variables, like paths or files to write, …

Thank for your help

Maybe I’ve found a way to do this with the combination of Read Binary File + Spreadsheet + Function nodes.

I write my settings in a setting.csv file with a setting;value; header.
Each line will contain a key/value pair of setting.

The Read Binary will load the file, the spreadsheet transform in a JSON way, and the Function will “squash” all the lines in a single JSON Object.

{
  "nodes": [
    {
      "parameters": {
        "filePath": "/data/settings.csv"
      },
      "name": "Read Binary File",
      "type": "n8n-nodes-base.readBinaryFile",
      "position": [
        1350,
        400
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "options": {}
      },
      "name": "Spreadsheet File",
      "type": "n8n-nodes-base.spreadsheetFile",
      "typeVersion": 1,
      "position": [
        1550,
        400
      ]
    },
    {
      "parameters": {
        "functionCode": "const newItems = [{ json: {} }];\nfor (const item of items) {\n  console.log(item);\n  newItems[0].json[item.json.setting] = item.json.value;\n}\nreturn newItems;"
      },
      "name": "Function",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1750,
        400
      ]
    }
  ],
  "connections": {
    "Read Binary File": {
      "main": [
        [
          {
            "node": "Spreadsheet File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Spreadsheet File": {
      "main": [
        [
          {
            "node": "Function",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

What do you think, is it a good way ?

You can just use environment variables. So if you set the environment variable:

export ASDF=test

and you then use the following expression anywhere inside of n8n {{$env['ASDF']}} then it will output test.

Is there a place in the documentation where it was written ?

I’m sorry if I missed it.

And if it’s missing, I could make a PR to add some documentation on it, if you guide me where to insert this part.

Currently it is only listed very shortly as part of available variables in Expressions here:
https://docs.n8n.io/nodes/node-basics.html#expressions

1 Like