Fix Codex Reconnecting Loop: Switch Network Protocol via Environment Variables

Fix Codex's repeated reconnection delays by switching from WebSocket to HTTP via .env environment variables.
Codex defaults to WebSocket for client-server communication, which frequently fails in enterprise networks or behind proxies — forcing users to sit through up to 5 reconnection attempts before it falls back to HTTP. This article explains the root cause and shows how to configure proxy-related environment variables in your .env file to make Codex use HTTP/HTTPS from the start, eliminating the wait entirely.
If you're a heavy Codex user, you've probably run into this scenario more than once: the chat interface gets stuck at Reconnecting... 2/5, 3/5, or all the way to 5/5. Each reconnection attempt takes several seconds, and over time, the cumulative wait adds up significantly. This article breaks down the root cause of this issue and offers a straightforward fix.
Root Cause: The Default WebSocket Protocol
After a major update, Codex switched to using WebSocket as the default communication protocol between client and server. WebSocket is a full-duplex, persistent connection protocol standardized by IETF in 2011 via RFC 6455. It builds on top of an HTTP upgrade handshake and enables low-latency bidirectional communication over a single TCP connection — commonly used in live chat, real-time collaborative editing, and stock ticker feeds.
In theory, WebSocket is ideal for real-time communication. But in environments with proxies, firewalls, or unstable networks, its connection reliability degrades noticeably. WebSocket relies on the HTTP/1.1 Upgrade mechanism, sending a special handshake request to "upgrade" an HTTP connection into a persistent bidirectional channel. In enterprise network environments, however, this mechanism faces numerous obstacles: corporate firewalls perform Deep Packet Inspection (DPI) on non-standard protocol headers; transparent proxies that aren't aware of the WebSocket handshake treat it like a regular HTTP connection and forcibly close it after an idle period; load balancers (such as older versions of Nginx or HAProxy with default configurations) may not forward the Upgrade header. Additionally, some ISP middleboxes send RST packets to long-lived TCP connections, causing WebSocket to silently disconnect.
The Deep Conflict Between WebSocket and Enterprise Networks
WebSocket's design philosophy prioritizes ultimate real-time performance, but its handshake mechanism creates structural tension with modern enterprise network security infrastructure. Deep Packet Inspection (DPI) technology can identify and reassemble application-layer protocols from TCP streams. Enterprise DPI devices (such as next-generation firewalls from Palo Alto, Fortinet, etc.) parse HTTP
Upgradeheaders and apply separate security policies to WebSocket traffic — sometimes silently dropping it due to misconfigured policies. Even more insidious is TLS interception and re-inspection (SSL Inspection): enterprise proxies act as man-in-the-middle, terminating the client's TLS connection and establishing a new TLS connection to the target server. During this process, WebSocket's persistent nature frequently conflicts with the proxy's connection pool management logic, leading to unpredictable disconnections. This explains why the same Codex installation might work perfectly on a home broadband connection yet trigger frequent reconnects on an office network.
When a WebSocket connection fails, Codex doesn't give up immediately — it retries up to 5 times, which is why you see Reconnecting... 1/5 through 5/5. This "retry then fallback" mechanism is quite common in the industry and is essentially a Transport Fallback strategy. The core idea is "prefer the optimal protocol first, then progressively degrade to more compatible alternatives upon failure."
The Engineering Evolution of Transport Fallback
The engineering practice of Transport Fallback traces back to the early 2010s, the "prehistoric era" of real-time web technology. At the time, the WebSocket standard wasn't yet widespread and browser implementations varied wildly. Socket.IO (born in 2010) made multi-protocol adaptation its core competitive advantage: it abstracted a unified event-driven API while attempting WebSocket, Flash Socket, XHR multipart streaming, XHR long-polling, and JSONP polling in sequence based on environment capabilities. Even though WebSocket support is now near 100%, this fallback philosophy has been preserved — because network complexity hasn't decreased with protocol standardization. If anything, it has increased with the proliferation of zero-trust architectures, SD-WAN, cloud proxies, and other new infrastructure layers.
Socket.IO is the canonical implementation of this pattern: it tries WebSocket first, then falls back to HTTP long-polling. HTTP long-polling works by having the client send a request that the server holds open — "hanging" the connection — until new data is available or a timeout occurs; the client immediately sends another request upon receiving a response, simulating real-time push. SSE (Server-Sent Events) is a unidirectional server push stream, also based on plain HTTP, with excellent compatibility. These alternatives' request-response model naturally penetrates almost all proxies, at the cost of HTTP header overhead on each transmission and slightly higher latency than WebSocket's native framing — but for AI conversations where each interaction takes relatively long, the extra few dozen milliseconds of latency is negligible. Stability is the primary metric.
The connection priority is typically: WebSocket (lowest latency) → HTTP Long Polling or SSE (Server-Sent Events). Only after all 5 WebSocket attempts fail does Codex automatically fall back to HTTP/HTTPS — which, ironically, is often faster and more stable in many network environments.

The fundamental issue is this: Codex has a more reliable HTTP channel available, yet it insists on exhausting all 5 WebSocket attempts before switching to it. For developers who run dozens of conversations daily, this unnecessary wait is amplified over and over, seriously degrading the user experience.
Can You Change the Default Connection Method?
Once the root cause is identified, the natural question is: can you make Codex use HTTP/HTTPS directly, skipping the WebSocket reconnection loop entirely?
The answer is yes — but with a caveat: there's currently no built-in settings UI to change this behavior directly. Codex doesn't provide a graphical toggle for "connection protocol." You need to go one level deeper and modify environment variables to influence its runtime behavior.

The core approach: Codex reads configuration files in the user's home directory at startup. We can inject network-related environment variables there to change how it selects a connection protocol.
Step-by-Step Instructions
Step 1: Locate and Edit the .env File
Navigate to the hidden configuration folder in your home directory and create or edit a file named .env. The .env file format dates back to around 2012, popularized by Heroku's twelve-factor app methodology and standardized by the dotenv gem in the Ruby ecosystem and the dotenv npm package in Node.js. Its core idea is to separate environment configuration from code, storing settings in plain KEY=VALUE format — making it easy to switch between deployment environments while keeping sensitive information out of version control.
Codex is built on the Electron framework. As a desktop application framework based on Chromium and Node.js, Electron's main process is essentially a Node.js process that fully inherits the process.env environment variable mechanism.
Environment Variable Mechanics in Electron Apps
Electron's dual-process architecture (Main Process + Renderer Process) handles environment variables in a specific way: the main process, running as a Node.js runtime, directly inherits the operating system's
process.envobject; the renderer process runs inside a Chromium sandbox and can only access main process environment variables via IPC channels (contextBridge). Codex reads the.envfile in the main process at startup and merges it intoprocess.env, meaning all network requests — whether made by the Electron main process or through Node.js child processes — are aware of proxy environment variables. It's worth noting that Node.js 18's nativefetchAPI (based onundici) differs subtly from the olderhttp.requestmodule in how it reads proxy variables:undicirelies more on explicit proxy configuration rather than automatically reading system environment variables. However, the network layer abstraction used by Codex typically handles this difference uniformly.
In the .env file, you need to configure network proxy-related environment variables. In the Node.js ecosystem, HTTP_PROXY, HTTPS_PROXY, and NO_PROXY are conventions inherited from Unix systems, originally used for proxy configuration in command-line tools like curl and wget. Major networking libraries such as axios, node-fetch, and undici (the underlying implementation of Node.js 18+ built-in fetch) automatically read these variables to determine request routing.
The Deep Mechanism of Proxy Environment Variables as Protocol Selection Signals
The influence of
HTTP_PROXYandHTTPS_PROXYenvironment variables on WebSocket connection behavior is fundamentally determined by how the HTTP CONNECT tunnel protocol works. When an application establishes a WebSocket connection through an HTTP proxy, it must first send aCONNECT target-host:443 HTTP/1.1request to have the proxy open a TCP tunnel, then complete the TLS handshake and WebSocket Upgrade inside that tunnel. However, many lightweight proxy implementations (including some locally self-signed proxies) don't fully support the CONNECT method for WebSocket's persistent characteristics — the proxy may close the tunnel prematurely after forwarding the Upgrade handshake due to connection timeout policies. When Codex's networking library detects this failure, it marks WebSocket as unavailable and enters HTTP long-polling mode directly. Therefore, configuring a nominal proxy address (even if that address doesn't actually exist or isn't needed) has one core effect: it activates the "proxy-aware path" in the code, triggering more conservative protocol selection logic — rather than actually routing traffic through a proxy.

This step is the crux of the entire solution. By using an environment variable to "guide" Codex toward the HTTP channel, you're essentially triggering the fallback behavior that would otherwise only kick in after 5 failed WebSocket reconnection attempts — at the very first connection instead.
Step 2: Restart the App for the Changes to Take Effect
Environment variable configurations are typically read at application startup, so after modifying the .env file, you need to fully quit and reopen Codex for the new configuration to take effect.
After restarting, initiate a conversation. The Reconnecting... x/5 sequence no longer appears — the connection is established almost instantly, and the speed improvement is immediately noticeable.

Results and Who This Helps
For occasional Codex users, a few seconds of reconnection delay may not matter much. But for power users who run large numbers of conversations in Codex every day, this change delivers a real, tangible improvement — it saves not just waiting time, but also the mental context that gets broken by frequent reconnection interruptions.
One important caveat: adjusting underlying behavior via environment variables is an "unofficial" technique. As Codex continues to be updated, the relevant configuration options and default protocol logic may change. If the Codex team eventually fixes WebSocket stability or provides a native protocol toggle, this workaround will become unnecessary. Back up your existing configuration before making changes so you can revert at any time if something goes wrong.
Summary
The value of this technique isn't in its complexity — it's in how precisely it targets a high-frequency pain point. It also reminds us that a tool's "default settings" aren't necessarily optimal for your specific network environment. Understanding how software selects connection protocols at a lower level — from the latency-optimization logic behind WebSocket's full-duplex-first strategy, to the compatibility fallback of HTTP long-polling's request-response model that punches through proxies, to how .env environment variables can quietly alter an Electron app's network behavior without touching source code — often helps us route around seemingly unsolvable wait times.
The next time you see Reconnecting... 5/5, try starting with the .env environment variable and proactively switching Codex's connection protocol to the more stable HTTP/HTTPS channel.
Key Takeaways
- Codex defaults to WebSocket, which is prone to frequent disconnections in enterprise networks, proxy environments, or behind firewalls — the root cause being structural conflicts between DPI inspection, SSL Inspection, and WebSocket's persistent connection characteristics
- The reconnection mechanism retries up to 5 times before falling back to HTTP/HTTPS; this transport fallback strategy inherited from the Socket.IO era represents a non-trivial time cost for power users
- By configuring proxy environment variables in the
.envfile in the user directory, you can activate the networking library's "proxy-aware path" and guide Codex to skip WebSocket and use the HTTP channel directly - Electron's dual-process architecture ensures that environment variables in
.envare visible to all network requests in the main process — this is the underlying mechanism that makes the solution work - This is an unofficial technique; back up your configuration and keep an eye on future Codex releases for official protocol optimization improvements
Related articles

Domain Renewal Jumps from $10 to $3,000: Exposing Hover's Renewal Trap and How to Protect Yourself
A Hover user's domain renewal jumped from $10 to $3,000. Learn about premium domain pricing, registrar traps, and practical strategies to protect yourself.

Vendor C++ Toolchains Silently Swallowing Compiler Warnings: Risks and Prevention Strategies
Analysis of how chip vendor C++ toolchains silently suppress compiler warnings, the risks involved, and prevention strategies including cross-validation and static analysis.

Vendor C++ Toolchains Silently Swallowing Compiler Warnings: Risks and Mitigation Strategies
Analysis of how chip vendor C++ toolchains silently suppress compiler warnings, the risks involved, and mitigation strategies using cross-validation and static analysis tools.