Introduction
Many developers working with Codex encounter a repetitive connection error sequence immediately after launching the application. The terminal prints five sequential retries: Reconnecting..1/5, Reconnecting..2/5, continuing through to Reconnecting..5/5. Even though the service usually succeeds after multiple attempts, this repeated reconnection cycle creates friction for daily development workflows. Users are forced to wait through several WebSocket handshake failures before the agent interface becomes usable.
This article explains the root cause of the Codex WebSocket reconnect loop, and presents a practical configuration method using an environment .env file. The solution preserves Codex’s native WebSocket communication mode, rather than disabling WebSocket entirely. By explicitly defining proxy addresses inside environment variables, all network traffic including WebSocket handshakes can route correctly through your local proxy service. This tutorial covers file creation, syntax rules, platform-specific paths, common pitfalls and validation steps for Windows, macOS and Linux environments.
For developers managing multiple AI service endpoints and proxy routing rules, an API gateway can streamline configuration management across agent clients. 4sapi, an API gateway, centralizes access control and traffic forwarding for various model services in similar agent workflows.
1. Problem Phenomenon and Root Cause Analysis
1.1 Symptom Description
The classic observable symptom occurs right after Codex startup. The console continuously outputs five reconnection attempts in order:
After finishing all five retry attempts, Codex eventually establishes a usable connection. The key detail is that standard HTTP and HTTPS API requests pass through the proxy normally, while WebSocket upgrade requests fail to leverage the same proxy settings.
This mismatch is the primary source of the issue. Regular REST requests respect the system proxy configuration, but WebSocket handshake operations do not inherit the proxy parameters automatically. Codex repeatedly tries to establish WebSocket connections without proxy forwarding. Each attempt times out, triggering the built-in retry counter, until fallback network logic activates and allows the connection to proceed.
The core fix strategy is straightforward: supply Codex with explicit HTTP and HTTPS proxy addresses via environment variables loaded before the application initializes its network stack. This forces WebSocket handshakes to use the same proxy tunnel as conventional web requests.
1.2 Key Background on WebSocket Proxy Handshake
WebSocket starts with an HTTP Upgrade request. Under normal proxy setups, this upgrade packet must be forwarded by the proxy server. If the application does not pass proxy environment variables to its network client, the upgrade request bypasses the proxy entirely. In restricted network environments, direct outbound connections will be blocked, leading to handshake timeouts.
Many desktop applications only read system-level proxy settings for basic HTTP traffic, and do not automatically apply those settings for WebSocket upgrade flows. Codex falls into this category. It does not automatically reuse OS proxy variables unless they are explicitly defined within its local .env configuration file. The five-step reconnection sequence is Codex’s native fault tolerance mechanism for network failures.
It is important to distinguish two possible remediation approaches. One approach disables WebSocket and falls back to polling transport, which avoids this issue but sacrifices the low-latency streaming benefits of WebSocket. The second method, which this guide focuses on, retains WebSocket functionality by properly configuring proxy environment variables. This is the preferred path for users who wish to keep Codex’s real-time streaming features intact.
2. Create the .env Configuration File
The .env file must be placed inside Codex’s dedicated configuration directory. File paths differ between operating systems. The following paths are the standard locations for each platform.
2.1 macOS and Linux Paths
For Linux systems:
For macOS systems:
Note the hidden folder .codex. The leading dot marks it as a hidden directory on Unix-like systems. File explorers on macOS and Linux hide folders starting with . by default, so you may need to toggle “show hidden files” to locate the directory.
2.2 Windows Path
On Windows, the .codex folder resides within your user profile directory:
Windows File Explorer also hides file extensions by default. This behavior creates one of the most frequent configuration mistakes covered in the next section.
3. Common Pitfall: How to Properly Create a File Named .env
Some users are unfamiliar with files that have no base filename and only an extension. A simple workaround is to first create a plain text .txt file, write the proxy configuration content inside, then rename the file.
Critical Warning for Windows Users
Windows File Explorer hides known file extensions by default. If you name your file .env while extension hiding is enabled, the actual filename becomes .env.txt. Codex cannot load or read .env.txt. The application only loads a file literally named .env.
How to verify and fix this:
- Open File Explorer, go to the View tab.
- Check the checkbox labelled “File name extensions”.
- Now you can see the full filename. Delete the
.txtsuffix so the final filename is only.env.
If you skip this step, the environment variables will never be loaded, and the reconnection loop will persist even after editing the file. This is the single most common reason users report the fix “not working”.
4. Content to Write Inside the .env File
Open your .env file with any plain-text editor such as Notepad, VS Code, Vim or Nano. Paste the three lines below. Replace 127.0.0.1:your-proxy-port with the actual listening address and port number from your local proxy software.
Explanation of each environment variable
- HTTP_PROXY: Defines the proxy address for unencrypted HTTP traffic.
- HTTPS_PROXY: Specifies the proxy tunnel for HTTPS requests, including the WebSocket upgrade handshake. Most local proxy clients use an HTTP forward proxy endpoint even for HTTPS tunneling, so the value format stays
http://. - NO_PROXY: Lists destinations that bypass the proxy. The entry
localhost,127.0.0.1,::1ensures local loopback addresses do not get sent through the proxy, preventing unnecessary routing loops for local services.
Make sure there are no extra spaces around the equals sign, and quotation marks are correctly placed. Some parsers are sensitive to whitespace. Invalid whitespace in .env will cause variables to load incorrectly.
5. How to Activate the Updated .env Configuration
Environment files are read during Codex startup. Changes will not take effect while the application is running. Follow this step-by-step workflow:
- Save the
.envfile and confirm there are no typos in proxy port or address. - Fully quit Codex. Closing only the window may leave background processes running; terminate all Codex related processes if necessary.
- Launch Codex again.
- Watch the startup console to check whether the continuous
Reconnecting..1/5 ~ 5/5sequence still appears.
If configured correctly, the WebSocket handshake completes on the first attempt, and the five retries no longer appear. Startup latency reduces noticeably.
6. Troubleshooting Checklist When the Fix Fails
If Codex still cycles through reconnect attempts after configuration, work through this checklist systematically.
6.1 Verify File Name and Location
- Confirm the filename is exactly
.env, not.env.txt. - Confirm the file sits inside
.codexfolder under your user home directory. - Confirm there is no duplicate
.envfile in other directories overriding your settings.
6.2 Validate .env Syntax
- Remove accidental trailing spaces at the end of each line.
- Check quotation marks: do not mix single quotes and double quotes unless your environment parser supports it.
- Confirm the proxy port matches the listening port of your local proxy software. Open your proxy client and verify it is active and listening on
127.0.0.1.
6.3 Test Proxy Connectivity Independently
Before testing Codex, validate your proxy works separately. You can test with curl in terminal:
If this curl command fails, the problem is with your proxy service itself, not Codex or the .env configuration. Resolve proxy connectivity first.
6.4 Check for Conflicting System Environment Variables
Operating system-level HTTP_PROXY variables can override the local .env file in certain builds of Codex. Check whether global environment variables are already defined, which may conflict with your custom proxy address.
6.5 Confirm WebSocket Support on Proxy
Not all proxy servers fully support the CONNECT method required for WebSocket tunneling. Older or simplified proxy tools may block upgrade requests. Confirm your proxy software supports WebSocket forwarding before continuing.
7. Technical Background: Why This Fix Works
Codex initializes its network client after loading variables from .env. When HTTP_PROXY and HTTPS_PROXY exist, the underlying HTTP client library uses the proxy for every outbound request, including the HTTP upgrade request that initiates WebSocket.
Without these variables, the WebSocket upgrade request tries to connect directly. In restricted network environments, direct outbound connections fail. Codex catches the connection error, increments the retry counter, and tries again. After five failed attempts, the client falls back to alternative transport mechanisms, which is why it eventually connects after the sequence completes.
By defining proxy rules explicitly, the WebSocket handshake passes through the same tunnel used for normal API requests. The handshake succeeds on the first try, eliminating the 1/5 to 5/5 retry sequence entirely.
This method preserves all native WebSocket advantages: low latency, real-time message streaming and bidirectional communication. If you disable WebSocket to bypass this error, you trade streaming responsiveness for connection reliability. The .env approach avoids that tradeoff.
8. Production Best Practices for Codex Network Configuration
- Separate environment configurations: Maintain different
.envtemplates for local development and remote deployment. Do not hardcode proxy ports inside source files. - Avoid committing .env to version control: The
.envfile can contain network routing and proxy details. Always add.envto.gitignoreif using git. - Monitor connection logs: Keep an eye on startup logs after deployment. Sudden reappearance of reconnect warnings often indicates proxy service crashes or port changes.
- Automate validation: For teams running Codex on multiple workstations, include a simple pre-start script that validates proxy reachability before launching the agent.
- Document proxy port conventions: Standardize local proxy port numbers across your team to reduce configuration mismatches.
For teams running multiple AI agent clients and model endpoints, centralized routing reduces manual per-client configuration work. Consistent forwarding rules can reduce WebSocket handshake failures across agent tools.
9. Conclusion
The repeating Reconnecting..1/5 ~5/5 warning in Codex stems from inconsistent proxy handling between regular HTTP requests and WebSocket upgrade handshakes. Using a .env file to inject proxy environment variables is a lightweight, non-intrusive solution. It keeps WebSocket enabled and removes the five-step retry loop at startup.
The procedure is cross-platform, applicable for Windows, macOS and Linux. The most frequent failure point is incorrect filename extension on Windows. Always enable file extension visibility to confirm the file is saved as .env.
If you have encountered this same WebSocket reconnection loop on Codex, this environment variable configuration is worth testing before switching to non-streaming transports. It preserves real-time streaming capability while stabilizing the initial connection handshake.
International access: https://4sapi.com
Domestic access: https://4sapi.cn




