How to Store a Proxy Password in .env: Python, Node and Git

Published:

11 minute read

Acar Diveroli
Written by: Acar Diveroli
A repo tray holds app.py and .gitignore, the .env slot empty; a blue .env block with a key sits outside, wired to the code

A .env file is a plain-text configuration file that keeps secrets such as a proxy username and password out of your code. The code reads these values from environment variables at runtime, and .gitignore keeps the file out of the repo. The trap is the password leaking another way: a proxy URL printed to a log line, or a file that was committed once. This post covers the .env setup, Python and Node examples, masking in logs and what to do after a leak.

.env and .gitignore

A .env file holds one NAME=value pair per line. A proxy needs four variables: host, port, username and password. Put the password in single quotes. You will see why below.

ini
# .env — never goes into the repo
PROXY_HOST=pr.proxynet.io
PROXY_PORT=8000
PROXY_USER=user
PROXY_PASS='pass@123'

Add three lines to .gitignore. The first two keep out .env and variants such as .env.local, the third brings the template file back. In our test, git check-ignore ignored both files, while .env.example was added to the repo.

text
.env
.env.*
!.env.example

.env.example holds the same names with empty values. A new developer copies it to .env and fills in their own credentials. The repo then documents which variables are needed.

ini
# .env.example — goes into the repo, holds no values
PROXY_HOST=pr.proxynet.io
PROXY_PORT=8000
PROXY_USER=
PROXY_PASS=

.gitignore only affects files that are not tracked yet, so it does nothing for a .env that was already committed. In our test we changed the file after adding the rule, and git status still showed it as modified (M). To stop tracking the file, run git rm --cached .env. The command does not delete the file from disk.

.env is for local development. On a server, the same variables come from the service manager's environment settings, your CI system's secret variables or your cloud's secret manager. The code stays the same, because it still reads environment variables. On a server with a fixed IP you may not need a password at all: authenticating with an IP whitelist leaves the URL without credentials.

python-dotenv in Python

python-dotenv is a package that reads a .env file and writes the values into os.environ. Install it with pip install python-dotenv. Called without arguments, load_dotenv() looks for .env starting in the script's folder and moving up through parent folders. In our test we ran the script from another folder and the file was still found.

python
import os
from urllib.parse import quote

import requests
from dotenv import load_dotenv

load_dotenv()  # finds and loads .env, does not override existing variables


def proxy_url() -> str:
    user = quote(os.environ["PROXY_USER"], safe="")
    password = quote(os.environ["PROXY_PASS"], safe="")
    host = os.environ["PROXY_HOST"]
    port = os.environ["PROXY_PORT"]
    return f"http://{user}:{password}@{host}:{port}"


proxy = proxy_url()
r = requests.get(
    "https://httpbin.org/ip",
    proxies={"http": proxy, "https": proxy},
    timeout=15,
)
print(r.status_code, r.text)

Read values with os.environ["NAME"], not os.getenv. A missing variable then raises a KeyError that names it right away. getenv returns None instead. A missing host puts the text None into the URL, a missing password makes quote raise an unrelated TypeError.

load_dotenv() does not override a variable that is already set in the environment. In our test, with PROXY_PASS=wrong set in the shell, the correct password in .env was ignored and the proxy returned 407. On a server this behavior helps: the real environment value always wins. If a stale variable is left over locally, pass override=True or remove the variable.

If you use the Proxynet SOCKS5 Proxy, only the scheme changes: build the URL with socks5h://. Requests needs the requests[socks] package for this scheme.

--env-file in Node.js

Node.js reads a .env file without any package. The command node --env-file=.env app.mjs loads the file into process.env. The flag arrived in v20.6.0 and dropped its experimental label in v24.10.0 and v22.21.0. If the file is missing, Node does not start. In our test we got the error missing.env: not found. If the file is optional, use --env-file-if-exists, added in v22.9.0.

js
// app.mjs — run with: node --env-file=.env app.mjs
import { ProxyAgent, fetch } from 'undici';

for (const name of ['PROXY_HOST', 'PROXY_PORT', 'PROXY_USER', 'PROXY_PASS']) {
  if (!process.env[name]) throw new Error(`${name} is not set`);
}

const proxy = new URL(`http://${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`);
proxy.username = process.env.PROXY_USER; // URL encodes special characters itself
proxy.password = process.env.PROXY_PASS;

const res = await fetch('https://httpbin.org/ip', {
  dispatcher: new ProxyAgent(proxy.href),
});
console.log(res.status, await res.text());

The loop at the top matters. JavaScript turns a missing variable in a template string into the text undefined without an error, and the URL breaks silently. The password field of the URL object does the percent-encoding itself. In our test, the password p@ss#1 was written as p%40ss%231 and the proxy received the original password.

To load the file from code instead of a flag, there is process.loadEnvFile() (v20.12.0 and v21.7.0). Its default path is ./.env, resolved against the working directory. In our test, running the script from the parent folder gave an ENOENT error. To look for the file next to the script, give the path relative to the module:

js
import { loadEnvFile } from 'node:process';

loadEnvFile(new URL('.env', import.meta.url));

Neither method overrides a variable already set in the environment. In our test, PROXY_PASS=wrong from the shell won with both.

Quotes and special characters

.env parsers read unquoted values differently. The difference shows most with the # sign. Node treats everything after # in an unquoted value as a comment. python-dotenv does so only when a space comes before it. We read the same lines with both tools:

.env linepython-dotenv 1.2.1Node 24
PROXY_PASS=p@ss#1p@ss#1p@ss ✗
PROXY_PASS=p@ss #1p@ss ✗p@ss ✗
PROXY_PASS='p@ss#1'p@ss#1 ✓p@ss#1 ✓
PROXY_PASS='x${A}y'xy ✗x${A}y ✓

The first row is a silent bug. A .env that works in Python sends a truncated password in Node, and the proxy returns 407. Always put the password in single quotes. The last row is python-dotenv's ${…} expansion, and it works inside single quotes too. If your password contains ${, pass load_dotenv(interpolate=False).

Keep the password unencoded in .env. Do the encoding when you build the URL: quote(password, safe="") in Python, the URL object in Node. An unencoded password splits the URL in the wrong place. In our test, with p@ss#1 written as is, Requests tried to resolve a server called ss. Part of the password ended up in the error message and in a DNS query. The full character table is in the post on the parts of a proxy URL.

Masking in logs

A proxy password usually leaks from your own log line, not from a library. In our test, Requests connection errors and urllib3 DEBUG records did not contain the password. undici's 407 error did not print the URL either. What printed the password was our own line, such as print(proxy).

If you need to show the URL, mask it first:

python
from urllib.parse import urlsplit, urlunsplit


def mask_proxy_url(url: str) -> str:
    parts = urlsplit(url)
    if parts.password is None:
        return url
    netloc = f"{parts.username}:***@{parts.hostname}"
    if parts.port:
        netloc += f":{parts.port}"
    return urlunsplit(parts._replace(netloc=netloc))


print(mask_proxy_url("http://user:pass%40123@pr.proxynet.io:8000"))
# http://user:***@pr.proxynet.io:8000

In Node the same job takes two lines with the URL object:

js
function maskProxyUrl(href) {
  const u = new URL(href);
  if (u.password) u.password = '***';
  return u.href;
}

Manual masking is easy to forget. In Python, a log filter catches every record. Attach the filter to the handler, not the logger. In our test this also masked a line coming from another library's logger.

python
import logging
import re

URL_CREDS = re.compile(r"(\w+://[^:/@\s]+:)[^@\s]+@")


class MaskProxyPassword(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.msg = URL_CREDS.sub(r"\1***@", record.getMessage())
        record.args = None
        return True


logging.basicConfig(level=logging.INFO)
for handler in logging.getLogger().handlers:
    handler.addFilter(MaskProxyPassword())

The filter only works fully on an encoded password. If the password contains a raw @, the pattern stops at the first @ and leaves the rest exposed. Use the masked URL in your own error messages too. Never log all of os.environ or process.env.

If the password reached the repo

A committed password is not safe until it is changed. Cleaning the history alone is not enough. The password remains in every clone pulled earlier, in forks and in CI logs. GitHub's documentation also lists revoking or rotating the secret as the first step.

In our test we removed .env with git rm --cached and committed. git show HEAD~2:.env still printed the old password. The file was gone from the latest commit, not from the history.

Do this in order:

  1. Rotate the password. Change the proxy password in your provider's dashboard. The old password stops working at that moment.
  2. Roll out the new password. Update your local .env, the server's environment variables and your CI secret variables.
  3. Stop tracking the file. Run git rm --cached .env and add the .gitignore rule.
  4. Clean the history if needed. Rewriting history makes the old password harder to find. This step needs coordination with your team, because everyone has to pull the repo again.
  5. Watch your usage. Over the next few days, check your traffic usage for an unexpected increase.

Troubleshooting

Most symptoms come from .env not being loaded at all, or being read the wrong way.

SymptomCauseFix
KeyError: 'PROXY_PASS'.env not loaded or wrong nameCheck the file path and variable name
.env: not found--env-file could not find the fileFix the path or use --env-file-if-exists
ENOENT … '.env'loadEnvFile() looks in the working directorynew URL('.env', import.meta.url)
.env is correct but 407A stale value is set in the environmentRemove the variable or use override=True
407 only in NodeUnquoted # read as a commentPut the password in single quotes
Unknown host in the errorPassword entered the URL unencodedquote(…, safe="") or URL
git status shows .envThe file is already trackedgit rm --cached .env

If you get a 407, first check which password the program actually sees. Printing the password's length or its first character gives you enough of a clue without printing the whole password.

How we tested

We ran the tests on December 2, 2026, on Windows 11. We used Python 3.13.17, python-dotenv 1.2.1, Requests 2.34.2, urllib3 2.6.3, Node.js 24.22.2, undici 8.10.2 and Git 2.56.0. We ran an HTTP proxy on 127.0.0.1 that required Basic authentication. The proxy decoded and logged the incoming username and password. The test password was p@ss#1. The target was a plain HTTP local address, so the CONNECT tunnel was outside this test. We compared .env parsing across python-dotenv's dotenv_values function, Node's util.parseEnv function and the --env-file flag. We tried the Git steps in a temporary repo. In the examples we replaced the local address with pr.proxynet.io:8000.

The bottom line

Keep the password in .env in single quotes, build the URL in code with encoding and only print the masked version to logs. On a server, use environment variables or a secret manager instead of .env. Above all, if the password was committed even once, change it before you clean the history. Once the setup is ready, you can send your first request with Residential Proxy.

Sources

Frequently asked questions

Is a .env file secure?

No, not on its own. .env is plain text and is not encrypted. Its safety comes from staying out of the repo and from limited access on the machine. Add the file to .gitignore and don't share it with anyone over chat or email. On Linux and macOS, set the file permissions so only you can read it. On a server, prefer environment variables or a secret manager to a plain file.

Should the proxy password in .env be quoted?

Yes, use single quotes. In an unquoted value, Node treats everything after # as a comment and truncates the password. In our test, the line PROXY_PASS=p@ss#1 was read as p@ss in Node and as p@ss#1 in python-dotenv. Single quotes gave the same result in both tools. If the password contains ${, python-dotenv expands that part, so turn it off with interpolate=False.

Should .env hold the encoded password?

No. Keep the original password in .env and do the encoding when you build the URL. In Python, urllib.parse.quote(password, safe="") does it, in Node the password field of the URL object. The original value is useful elsewhere too, for example in curl's --proxy-user option. If you store the encoded value, you risk encoding it twice.

Do I still need the dotenv package in Node.js?

Not in most projects. Node v20.6.0 and later reads .env without a package through the --env-file flag, and v20.12.0 and later through process.loadEnvFile(). These features dropped their experimental label in v24.10.0 and v22.21.0. If you use an older Node version or need an extra feature such as variable expansion, the package is still useful.

Is deleting the file enough if the password reached GitHub?

No. A new commit that deletes the file does not remove the password from the old commit. In our test, git show still printed the old password after the deletion. Rewriting history does not remove the password from clones and forks either. The first step is to rotate the password in your provider's dashboard. Once the old password is invalid, the copy in the history is useless.

How do I use .env in Docker or CI?

Pass the values through the environment's own secret variables, not through a .env file. Most CI systems put secret variables into the environment during the job and hide them in logs. A container takes the variables from outside at runtime, and .env is not copied into the image. The code still reads os.environ or process.env, only the source of the value changes. Adding the file to the image writes the password into the image layers.

Ask ChatGPTAsk Claude