Managing Proxy Credentials with Environment Variables
Hardcoded proxy passwords end up in Git history, logs and screenshots. This guide shows a safer pattern using environment variables, with naming, loading, masking and rotation.
9 min readUpdated Nov 14, 2026By XPASS Editorial Team

A proxy needs a host, a port and, in most setups, a username and password. The quickest way to get a script working is to paste all four into the source file. It works on the first try, and that convenience is exactly how proxy passwords end up in Git repositories, in screenshots, in support tickets and in log files. Someone who later gets access to any of those copies gets access to your proxy account too.
This guide shows a safer and still simple pattern: keep credentials in environment variables, load them at startup, validate them, mask them in output, and rotate them when needed. It is aimed at developers and operators who use proxies for lawful work, such as testing, quality assurance or monitoring of sites that allow it. The same ideas apply whether you write a small script, a scheduled job or a service.
Why hardcoded credentials cause trouble
Think about every place a source file travels.
- Version control: once a secret is committed, it stays in the history. Deleting the line in a later commit does not remove it from older ones, and forks and clones keep their own copies.
- Collaboration: files get pasted into chats, shared in code reviews, and attached to bug reports. Few people scrub them before sending.
- Build and deploy systems: build logs sometimes print configuration. A secret in code can end up in a log that many people can read.
- Backups and editors: cloud sync, editor history and local backups all hold copies you may forget about.
- Changes: when the password changes, you must edit and redeploy code in every place it was copied. People then skip the change, and old passwords live on.
Separating configuration from code, a principle often summarised as "store config in the environment", solves many of these problems at once. The code stays the same across development, testing and production, and only the surrounding configuration changes.

What counts as a proxy credential
Treat these values as sensitive, though to different degrees.
| Value | Sensitivity | Notes |
|---|---|---|
| Password | High | Never log, never commit, never put in a URL you print |
| API token or key | High | Same handling as a password |
| Username | Medium | Often identifies your account; mask it in shared output |
| Full proxy URL with credentials | High | Contains the password; build it at runtime, never store the string |
| Host and port | Low to medium | Usually safe to log, but still part of your setup |
| Session or region labels | Low | Useful for debugging and generally safe to log |
The full proxy URL deserves a warning. A string like scheme://username:password@host:port is convenient, but it puts the password into a single value that tends to be logged, printed on errors and copied into tools. Store the parts separately and join them only at the moment you create the client.
Naming and structure
Good names make configuration self-explanatory and prevent mistakes.
- Use one variable per value: PROXY_HOST, PROXY_PORT, PROXY_USERNAME, PROXY_PASSWORD, and optionally PROXY_SCHEME for http or socks5.
- If you use several proxies or regions, add a clear prefix or suffix, such as PROXY_EU_HOST and PROXY_US_HOST, rather than a long, unreadable list.
- Keep names uppercase with underscores, which is the common convention across operating systems and platforms.
- Do not put the environment in the password itself. Separate variables or separate files for development and production are easier to reason about.
- Add a short README note or an example file listing the required variable names with fake placeholder values, so a new teammate knows what to set without seeing a real secret.
Loading variables step by step
The details differ by language and platform, but the sequence is the same.
- Decide where the values come from in each environment. On your laptop, this may be a local file that is excluded from version control. In a hosted environment, it is usually the platform's secret or environment settings. In a container, it is passed at start. On a server, it may be a protected service file.
- Add the local file name to your ignore list before you create it, so you cannot commit it by accident. Check that the ignore rule works by looking at the status of your repository.
- Read the values once at startup, into a small configuration object. Do not scatter reads across the code.
- Validate them. If a required variable is missing or empty, stop with a clear message that names the variable but never prints any value.
- Build the proxy client from the configuration. Join host, port and credentials only inside the code that creates the client.
- Pass the client to the rest of the program. No other part needs to know the password.
A short plain-language example helps. Imagine a script that fetches a page through a proxy for a regional layout check. At startup, it reads the four proxy variables. If PROXY_PASSWORD is missing, it prints "Missing required setting: PROXY_PASSWORD" and exits. If all are present, it creates an HTTP client with the proxy set, and from then on the rest of the script just calls the client. When the script fails, the error message mentions the host and the HTTP status but not the credentials.
If you handle many scripts, a small shared function that loads and validates proxy settings avoids copy-paste differences between them.
Keep secrets out of logs, errors and screenshots
Loading the secret safely is only half the work. The other half is not leaking it afterward.
- Never print the configuration object as a whole. A debugging line such as "config = ..." is a common leak.
- Mask when you must show something. For a username, show the first character and a few asterisks. For a password, show nothing at all.
- Check error messages. Some HTTP libraries include the full proxy URL, with credentials, in exception text. Catch exceptions near the client and rewrite the message.
- Review logging of requests. If you log request headers, remember that the Proxy-Authorization header carries credentials when basic authentication is used with an HTTP proxy. RFC 9110 describes this header and the 407 response that asks for it. Exclude it from logs.
- Be careful with shell history. A command like export PROXY_PASSWORD=... typed in a terminal can be saved in the history file. Use a file loaded by your tooling, a prompt that does not echo, or a history setting that ignores commands starting with a space, depending on your shell.
- Scrub screenshots and shared terminals before posting them.
For a deeper treatment of what to write in proxy logs and how long to keep them, see the article on collecting proxy logs without exposing user data; that guide pairs naturally with this one, though it is not required reading here.
Limits of environment variables
Environment variables are a good basic step, not a complete secrets solution. Know where they fall short.
- Process visibility: on some systems, other users or tools with enough privilege can read a process's environment. Restrict who has access to the machine.
- Inheritance: child processes inherit the environment by default. If your program launches other programs, they may receive the secret even when they do not need it. Pass only what is necessary.
- Dumps and diagnostics: crash reports, debug endpoints and "print all environment variables" diagnostics can expose everything. Disable or protect them.
- No audit trail: a plain variable has no record of who read it or when. A dedicated secrets manager offers access control, auditing and rotation features.
- Shared files: a local file with secrets is still a file. Give it restrictive permissions, and do not sync it to shared folders.
If your platform offers a secrets manager or encrypted settings, use it for production, and let your code still read from the environment at runtime. That keeps the application simple while the storage layer improves.
Rotation and incident response
Plan for the day a credential must change, because that day will come.
- Know where the credential is used. A short inventory of scripts, jobs and services saves a lot of time.
- Rotate on a schedule that fits your risk, and immediately after any suspected exposure, a departure of someone with access, or a leak in a log or repository.
- Change the password in your provider's account area, then update each environment's variable. Restart processes that read the variable only at startup.
- Verify after the change. A scheduled check, as described in the article on automated proxy health check testing, shows quickly whether a service is still authenticating correctly or is now receiving 407 responses.
- Search logs, repositories and shared documents for the old value and remove or redact what you find. Removing a commit from the latest branch is not enough if copies exist elsewhere, which is why the old credential must be invalidated.
- Review recent usage for anything you do not recognise, and write a short note about what happened and what you changed.
A small worked example shows the pattern. Suppose a team keeps a script that checks public pages through a proxy. Instead of writing the address in the code, the script reads PROXY_HOST, PROXY_PORT, PROXY_USER and PROXY_PASS at startup and stops with a clear message, without printing the values, if any is missing. A file named .env.example lists the four names with placeholder values and is committed to the repository, while the real .env file is listed in .gitignore. Each environment, such as a laptop, a test server and a production job, has its own values, so a leak from one does not expose the others. When the password changes, only the variable changes and the code stays as it is.
Finally, add a startup check that confirms the variables exist and have a plausible shape, such as a non-empty host and a numeric port, so a misconfigured environment fails early with a clear message instead of producing confusing 407 errors later.
Use credentials with care in tests and documentation
Tests should not require the real password. Use a fake proxy or a local test server, and keep real-credential checks in a separate, clearly marked job. Documentation and examples should use obvious placeholders such as your-username and your-password. When you share work for review, such as a redirect test for a regional site as described in the guide on checking geo-specific redirects with a proxy, share the script and a sample file with placeholders, never your real settings.
Summary
Keeping proxy credentials in environment variables separates secrets from code, makes configuration easy to change, and reduces the number of places a password can leak from. Use clear variable names, store the parts rather than a full URL, load once at startup, validate with messages that never print values, and build the client in a single place. Keep secrets out of logs, error messages, shell history and screenshots, remember that environment variables have limits and benefit from a secrets manager in production, and have a rotation plan ready. Use proxies only for lawful work and within each site's terms. If you are choosing a proxy for a project like this, the Proxy page shows what is on offer.
Frequently asked questions
Why should proxy credentials not be written in code?
Code is copied, committed to version control, shared in chats and pasted into bug reports. A password written in a source file travels with all of those copies and stays in Git history even after you delete it. Configuration outside the code keeps the secret in fewer places.
Are environment variables completely safe for secrets?
No. They are better than hardcoding, but they can still leak through process listings, crash dumps, debug output and child processes. Treat them as one layer: limit who can read them, never print them, and use a secrets manager where your platform offers one.
How should I name proxy environment variables?
Use clear, consistent names such as PROXY_HOST, PROXY_PORT, PROXY_USERNAME and PROXY_PASSWORD, with a prefix per environment or purpose if you have several. Keep the password separate from the host so you can log the host safely.
What should I do if a proxy password was exposed?
Rotate it immediately in your provider's account area, update the variable in every place that uses it, check logs and repositories for copies, and review recent usage for anything you do not recognise. Deleting the commit alone is not enough.
References
About the author

Bob Kanokphon Thongdee
- Founder of XPASS VPN
- Co-founder of eSIMonline.asia
- More than 7 years in online marketing
- Founder of Cojourney Visa and Cojourney Travel
Need a proxy for this?
XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.
See proxy plansKeep reading

Proxy Guides
How to Check Geo-Specific Redirects with a Proxy
Many sites send visitors to different pages by country or language. This guide shows how to use a proxy to observe those redirects step by step and record what you find.
10 min read

Proxy Guides
Using a Proxy with Serverless Functions Without Timeouts
Serverless functions have strict time limits, and a proxy adds another hop. This guide explains how to plan time budgets, split jobs, retry safely and keep proxy calls inside the limit.
10 min read

Proxy Guides
How to Automate Proxy Health Check Testing
A proxy that worked yesterday may fail today. This guide shows how to design a small, polite health check that tests connectivity, exit IP, latency and errors on a schedule.
10 min read