react-native-nitro-net
v0.3.1
Published
Ultra-high-performance networking to React Native by combining a memory-safe Rust core with the zero-overhead Nitro Modules JSI bridge. Provides Node.js-compatible net, tls, http(s) API.
Maintainers
Readme
react-native-nitro-net
Ultra-high-performance networking to React Native by combining a memory-safe Rust core with the zero-overhead Nitro Modules JSI bridge. Provides Node.js-compatible net, tls, http(s) API.
Features
- 🚀 High Performance: Built on top of Rust's
tokioasynchronous runtime. - 🤝 Node.js Compatible: Implements standard
net,tls,http, andhttpsAPIs. - 🛡️ Modern Security: TLS implementation powered by Rustls 0.23 (Ring provider), supporting TLS 1.2 and 1.3.
- 🔒 Full Protocol Support: Support for PEM/PFX certificates, SNI, HTTP Trailers, 100 Continue, Protocol Upgrades (101), and HTTP Tunneling (CONNECT).
- ⚡ Nitro Modules: Uses JSI for zero-overhead communication between JavaScript and Native code.
- 🛡️ Robust & Stable: Advanced fixes for port reuse, deadlocks, and connection pooling hangs.
- 📱 Cross-Platform: Supports both iOS and Android.
Installation
npm install react-native-nitro-net
# or
yarn add react-native-nitro-netiOS
Requires pod install to link the native libraries.
cd ios && pod installArchitecture
This library uses a high-performance three-layer architecture:
- JavaScript Layer: Provides high-level Node.js compatible
netandtlsAPIs usingreadable-streamandEventEmitter. - C++ Bridge (Nitro): Handles the zero-copy orchestration between JS and Rust using Nitro Hybrid Objects and JSI.
- Rust Core: Implements the actual networking logic using the Tokio asynchronous runtime, providing memory safety and high concurrency.
Usage
Client (Socket)
import net from 'react-native-nitro-net';
const client = net.createConnection({ port: 8080, host: '1.1.1.1' }, () => {
console.log('Connected!');
client.write('Hello Server!');
});
client.on('data', (data) => {
console.log('Received:', data.toString());
});
client.on('error', (err) => {
console.error('Error:', err.message);
});Server (Dynamic Port Support)
The server supports binding to a dynamic port by using 0.
import net from 'react-native-nitro-net';
const server = net.createServer((socket) => {
socket.write('Echo: ' + socket.read());
});
// Use 0 for dynamic port allocation
server.listen(0, '127.0.0.1', () => {
const address = server.address();
console.log(`Server listening on dynamic port: ${address?.port}`);
});TLS (Secure Socket)
import { tls } from 'react-native-nitro-net';
// Client connection
const socket = tls.connect({
host: 'example.com',
port: 443,
servername: 'example.com', // SNI
}, () => {
console.log('Securely connected!');
console.log('Protocol:', socket.getProtocol());
});
// Server with PFX
const server = tls.createServer({
pfx: fs.readFileSync('server.pfx'),
passphrase: 'your-password'
}, (socket) => {
socket.write('Secure hello!');
});
server.listen(443);- Advanced Features: Supports
keylogevent re-emission for Wireshark, session resumption, andasyncDispose. - Performance Tuning: Configurable
headersTimeout,keepAliveTimeout, andrequestTimeout. - Resource Management: Strict protective shutdown logic in Rust to prevent socket and Unix domain socket file leaks.
Usage
HTTP Request
Implementation of the standard Node.js http API.
import { http } from 'react-native-nitro-net';
http.get('http://google.com', (res) => {
console.log(`Status: ${res.statusCode}`);
res.on('data', (chunk) => console.log(`Body segment: ${chunk.length} bytes`));
res.on('end', () => console.log('Request complete'));
});HTTPS with Connection Pooling
Uses https and the built-in Agent for connection reuse.
import { https } from 'react-native-nitro-net';
const agent = new https.Agent({ keepAlive: true });
https.get('https://api.github.com/users/margelo', { agent }, (res) => {
// ... handle response
});TCP Client (Socket)
import net from 'react-native-nitro-net';
const client = net.createConnection({ port: 8080, host: '127.0.0.1' }, () => {
client.write('Hello Server!');
});Server (Dynamic Port Support)
The server supports binding to a dynamic port by using 0.
import net from 'react-native-nitro-net';
const server = net.createServer((socket) => {
socket.write('Echo: ' + socket.read());
});
server.listen(0, '127.0.0.1', () => {
const address = server.address();
console.log(`Server listening on dynamic port: ${address?.port}`);
});Compatibility Notes
[!IMPORTANT]
Server.close()Behavior: Unlike Node.js's default behavior whereserver.close()only stops accepting new connections, this implementation immediately destroys all active connections whenclose()is called. This ensures clean resource release and is more intuitive for mobile applications.
API Reference
net.Socket
| Property / Method | Description |
| --- | --- |
| connect(options) | Connect to a remote host/port or Unix path. |
| write(data) | Send data asynchronously. Supports backpressure. |
| destroy() | Immediate closing of the socket and resource cleanup. |
| setNoDelay(bool) | Control Nagle's algorithm. |
| setKeepAlive(bool)| Enable/disable keep-alive. |
| address() | Returns { port, family, address } for the local side. |
Events: connect, ready, data, error, close, timeout, lookup.
tls.TLSSocket
Extends net.Socket
| Property / Method | Description |
| --- | --- |
| authorized | true if peer certificate is verified. |
| getProtocol() | Returns negotiated TLS version (e.g., "TLSv1.3"). |
| getCipher() | Returns current cipher information. |
| getPeerCertificate()| Returns detailed JSON of the peer certificate. |
| getSession() | Returns the session ticket for resumption. |
| encrypted | Always true. |
Events: secureConnect, session, keylog, OCSPResponse.
Global APIs
| Method | Description |
| --- | --- |
| initWithConfig(options) | Optional. Initializes the Rust runtime with custom settings (e.g., workerThreads, debug). Must be called before any other operation. |
| setVerbose(bool) | Toggle detailed logging for JS, C++, and Rust. |
| isIP(string) | Returns 0, 4, or 6. |
net.Server
| Method | Description |
| --- | --- |
| listen(options) | Start listening. Supports port: 0 for dynamic allocation. |
| close() | Stops the server and destroys all active connections. |
| address() | Returns the bound address (crucial for dynamic ports). |
| getConnections(cb)| Get count of active connections. |
| renegotiate(opt, cb)| Shim: Returns ERR_TLS_RENEGOTIATION_DISABLED (Rustls security policy). |
Events: listening, connection, error, close, connect (HTTP Tunneling).
tls.Server
Extends net.Server
Supported methods: listen, close, addContext, setTicketKeys, getTicketKeys.
Events: secureConnection, keylog, newSession.
Debugging
Enable verbose logging to see the internal data flow across JS, C++, and Rust:
import { setVerbose } from 'react-native-nitro-net';
setVerbose(true);Logs will be visible in your native debugger (Xcode/logcat) and JS console, prefixed with [NET DEBUG] or [NET NATIVE].
License
ISC
