huytdps13400/react-native-ssl-manager / .agents/skills/nitro-fetch
nitro-fetch
VerifiedFast native networking primitives for React Native built on Nitro Modules — react-native-nitro-fetch, react-native-nitro-websockets, and react-native-nitro-text-decoder. Covers the fetch API, global replacement, prefetching and cold-start cache warming, the NitroWebSocket class and pre-warming, migrating from React Native's built-in WebSocket, the in-process NetworkInspector, native Perfetto / Instruments tracing, the native TextDecoder, and plugging nitro-fetch into axios via a custom adapter.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 6.0 KB |
| references/axios-adapter.md | markdown | 7.8 KB |
| references/migrate-from-rn-ws.md | markdown | 8.5 KB |
| references/network-inspector.md | markdown | 9.9 KB |
| references/perfetto-profiling.md | markdown | 10.1 KB |
| references/prefetching.md | markdown | 19.6 KB |
| references/text-decoder.md | markdown | 6.2 KB |
| references/using-websockets.md | markdown | 8.9 KB |
| references/websocket-prewarm.md | markdown | 8.5 KB |
references/websocket-prewarm.md
View on GitHub---
id: websocket-prewarm
title: Pre-warming WebSockets before React Native boots
scope: react-native-nitro-websockets
keywords: websocket, prewarm, cold start, libwebsockets, wss, handshake
---
# Pre-warming WebSockets
## Mental model
A WebSocket handshake on a cold start has to wait for: TCP connect, TLS handshake, HTTP upgrade, server-side auth. On a slow network and a TLS endpoint, that's easily 500–1500 ms — and it can't even *begin* until React Native has loaded enough to run your `new WebSocket()` line.
The pre-warmer cuts that delay to roughly zero by doing two things:
1. **Persist intent.** You tell it once (after login, say) that "this URL should be open on every cold start". It writes the URL + headers to native storage.
2. **Native bootstrap.** On the *next* launch, before the JS engine even runs, native code reads the queue and opens the connection on a background C++ service thread. Anything the server pushes during boot is buffered.
3. **JS adoption.** Later, when your screen runs `new NitroWebSocket(sameUrl, ...)`, the constructor finds the warm `wsi`, takes ownership (`lws_set_wsi_user`), and replays buffered messages onto your `onmessage` handler.
The user code is ordinary — no `await`, no special "warm socket" type. The pre-warmer is a side-channel optimisation; if it doesn't kick in (first install, no queue entry, URL mismatch), construction falls back to opening fresh.
This is for the *next* launch, not the current one. Pre-warming and immediately constructing a `NitroWebSocket` does nothing useful.
## Why pre-warm
- **The TLS handshake is the slowest part of opening `wss://`** — pre-warming runs it on a background thread before React Native finishes booting, so the JS code that constructs the socket gets an already-`OPEN` connection.
- **Server messages received during boot are buffered.** If your backend pushes a snapshot the moment the socket connects, you don't lose it — the JS handler replays it after adoption.
- **Zero JS-side complexity.** Your screen still calls `new NitroWebSocket(url, ...)`; the adoption is invisible to your code.
- **Survives app restarts.** Schedule the pre-warm once after sign-in and every subsequent cold start gets the win.
- **Combines with token refresh** so pre-warmed sockets still authenticate correctly after long idle periods.
## Setup
### iOS — automatic
iOS auto-bootstraps via `+load` in [`packages/react-native-nitro-websockets/ios/NitroWSAutoBootstrap.mm`](https://github.com/margelo/react-native-nitro-fetch/blob/main/packages/react-native-nitro-websockets/ios/NitroWSAutoBootstrap.mm). Nothing to wire.
### Android — one line in `Application.onCreate`
```kotlin
import com.margelo.nitro.nitrofetchwebsockets.NitroWebSocketAutoPrewarmer
class MainApplication : Application(), ReactApplication {
override fun onCreate() {
super.onCreate()
NitroWebSocketAutoPrewarmer.prewarmOnStart(this)
loadReactNative(this)
}
}
```
Reference: [`example/android/app/src/main/java/nitrofetch/example/MainApplication.kt`](https://github.com/margelo/react-native-nitro-fetch/blob/main/example/android/app/src/main/java/nitrofetch/example/MainApplication.kt).
If you skip this on Android, the JS API silently writes to disk and nothing on the native side ever reads it back.
## API
```ts
import {
prewarmOnAppStart,
removeFromPrewarmQueue,
clearPrewarmQueue,
} from 'react-native-nitro-websockets';
```
| Function | Behaviour |
|---|---|
| `prewarmOnAppStart(url, protocols?, headers?)` | Persist this entry. Synchronous; no return value. Replaces an existing entry with the same URL. |
| `removeFromPrewarmQueue(url)` | Drop one entry. No-op if it isn't there. |
| `clearPrewarmQueue()` | Wipe the queue. |
Source: [`packages/react-native-nitro-websockets/src/prewarm.ts`](https://github.com/margelo/react-native-nitro-fetch/blob/main/packages/react-native-nitro-websockets/src/prewarm.ts).
## Recipes
### Schedule a pre-warm after sign-in
```ts
import { prewarmOnAppStart } from 'react-native-nitro-websockets';
function onLoginSuccess(token: string) {
prewarmOnAppStart(
'wss://stream.example.com/feed',
['v1.feed.proto'],
{
Authorization: `Bearer ${token}`,
'X-Client': 'mobile',
},
);
}
```
### Adopt the warm connection
The screen that opens the WebSocket doesn't need to know whether the connection is warm or cold — it constructs `NitroWebSocket` the same way. The native layer hands over the warm `wsi` if the URL matches.
```ts
import { NitroWebSocket } from 'react-native-nitro-websockets';
const ws = new NitroWebSocket(
'wss://stream.example.com/feed', // ← must match exactly
['v1.feed.proto'],
{ Authorization: `Bearer ${token}` },
);
ws.onopen = () => {
// May fire immediately on adoption (the connection is already open).
};
ws.onmessage = (e) => {
// Includes buffered messages from before JS was ready.
if (e.isBinary) handleBinary(e.binaryData!);
else handleText(e.data);
};
```
### Adoption via explicit `NitroWebSocket` call sites
Pre-warmed connections are adopted the moment your code calls `new NitroWebSocket(url, ...)` with a matching URL. The adoption happens on the native service thread — you don't have to wait for "open" yourself.
```ts
import { NitroWebSocket } from 'react-native-nitro-websockets';
const ws = new NitroWebSocket('wss://stream.example.com/feed', ['v1.feed.proto']);
// ↑ adopts the warm connection if the URL matches the prewarm queue
```
Libraries that accept an injectable constructor (`socket.io-client`, `centrifuge-js`, and similar) can be pointed at `NitroWebSocket` the same way — pass it as the library's `WebSocket` option so its internal `new WebSocket(...)` becomes `new NitroWebSocket(...)`. Don't swap `globalThis.WebSocket`; it breaks devtools and hot reload and hides which code paths actually use the native socket.
### Tear down on logout
```ts
import { clearPrewarmQueue, removeFromPrewarmQueue } from 'react-native-nitro-websockets';
function onLogout() {
clearPrewarmQueue();
}
// Or selectively:
removeFromPrewarmQueue('wss://stream.example.com/feed');
```
If you forget, the next cold start tries to reconnect with a stale auth header.
### Refresh tokens before replay
If your stored auth header expires, register a token-refresh config (see `docs-website/docs/token-refresh.md`). The native bootstrap calls the refresh endpoint first, then replays the queue with the fresh headers.
## Gotchas
- **URL mismatch kills adoption.** `wss://example.com/feed` and `wss://example.com/feed/` (trailing slash) are different. Match them character-for-character.
- **Wiring missed on Android.** No crash, no log — just silently no pre-warm. The single line in `Application.onCreate` is the difference between "works" and "did nothing".
- **Pre-warming the current launch.** It only helps the *next* cold start. There's nothing to do for the launch you're currently in.
- **Stale headers.** Whatever you stored is what gets used. Either rotate quickly enough that they stay fresh, or wire token refresh.
- **Too many entries.** Each entry opens a real socket on cold start. Stick to one or two streams that actually matter.
- **`onopen` race.** If the warm socket is already `OPEN` by the time you assign `onopen`, the JS class still fires it for you (it buffers internally). Just assign your handlers synchronously after construction and don't worry about it.
## Pointers
- JS: [`packages/react-native-nitro-websockets/src/prewarm.ts`](https://github.com/margelo/react-native-nitro-fetch/tree/main/packages/react-native-nitro-websockets/src/prewarm.ts)
- Android bootstrap: [`packages/react-native-nitro-websockets/android/src/main/java/com/margelo/nitro/nitrofetchwebsockets/NitroWebSocketAutoPrewarmer.kt`](https://github.com/margelo/react-native-nitro-fetch/tree/main/packages/react-native-nitro-websockets/android/src/main/java/com/margelo/nitro/nitrofetchwebsockets/NitroWebSocketAutoPrewarmer.kt)
- iOS bootstrap: [`packages/react-native-nitro-websockets/ios/NitroWSAutoBootstrap.mm`](https://github.com/margelo/react-native-nitro-fetch/tree/main/packages/react-native-nitro-websockets/ios/NitroWSAutoBootstrap.mm)
- C++ singleton: [`packages/react-native-nitro-websockets/cpp/WebSocketPrewarmer.hpp`](https://github.com/margelo/react-native-nitro-fetch/tree/main/packages/react-native-nitro-websockets/cpp/WebSocketPrewarmer.hpp)
- Working example: [`example/src/screens/WebSocketScreen.tsx`](https://github.com/margelo/react-native-nitro-fetch/tree/main/example/src/screens/WebSocketScreen.tsx)
- Related: [`using-websockets.md`](./using-websockets.md), [`migrate-from-rn-ws.md`](./migrate-from-rn-ws.md)
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |