Networking
The react-native-webworker library includes built-in networking support for your worker threads. Every worker automatically gets the familiar browser fetch() API.
How it works
Section titled “How it works”Every worker comes with a complete Fetch API implementation built-in. Behind the scenes, it uses the platform’s native networking:
- iOS: Uses
NSURLSessionfor HTTP requests - Android: Uses
OkHttpfor HTTP requests
This ensures good performance and handles platform-specific requirements like SSL certificates, proxy settings, and connection reuse.
Fetch API
Section titled “Fetch API”Workers include a basic Fetch API for making HTTP requests. It is a simplified version compared to the full browser implementation.
Basic usage
Section titled “Basic usage”Here is how to make requests:
// Simple GET requestconst response = await fetch('https://jsonplaceholder.typicode.com/todos/1');const data = await response.json();console.log(data);
// POST request with JSON dataconst response = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 })});
if (response.ok) { const result = await response.json(); console.log(result);}Supported options
Section titled “Supported options”Currently, these fetch options work:
const response = await fetch('https://api.example.com/data', { method: 'POST', // HTTP method like 'GET', 'POST', 'PUT', 'DELETE' headers: { 'Authorization': 'Bearer token123', 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }), // String or ArrayBuffer timeout: 5000, // Request timeout in milliseconds redirect: 'follow', // 'follow', 'error', or 'manual' (Android only currently) mode: 'cors' // Accepted but ignored (Native requests are not subject to CORS)});Response format
Section titled “Response format”The fetch() function returns a basic response object with these properties:
const response = await fetch('https://api.example.com/data');
// Basic response infoconsole.log(response.status); // 200console.log(response.ok); // true (quick way to check if status is 200-299)
// Get response headers (as a plain object)console.log(response.headers['content-type']); // 'application/json'
// Read the response bodyconst text = await response.text(); // Get as plain textconst json = await response.json(); // Parse as JSONconst arrayBuffer = await response.arrayBuffer(); // Get as ArrayBufferError handling
Section titled “Error handling”Fetch provides basic error handling:
try { const response = await fetch('https://api.example.com/data');
if (!response.ok) { // Check for HTTP errors (like 404, 500, etc.) throw new Error(`HTTP ${response.status}: ${response.statusText}`); }
const data = await response.json(); console.log(data);
} catch (error) { // Network errors (DNS failure, connection issues, etc.) console.error('Request failed:', error.message);}Request body types
Section titled “Request body types”You can send different types of data in your requests:
Text and JSON
Section titled “Text and JSON”// Plain textawait fetch('/api', { method: 'POST', body: 'Hello World'});
// JSON objects (automatically converted to strings)await fetch('/api', { method: 'POST', body: { message: 'Hello' } // Gets turned into '{"message":"Hello"}'});Binary data
Section titled “Binary data”// ArrayBufferconst buffer = new ArrayBuffer(1024);await fetch('/api/upload', { method: 'POST', body: buffer});
// Typed arraysconst uint8Array = new Uint8Array([1, 2, 3, 4]);await fetch('/api/upload', { method: 'POST', body: uint8Array});Current limitations
Section titled “Current limitations”- Limited Fetch Options: Advanced options like
credentialsandsignalaren’t supported yet. - No XMLHttpRequest: The XMLHttpRequest API isn’t implemented.
- No AbortController: Request cancellation isn’t available yet.
- No Request/Response Classes: You can’t create
new Request()ornew Response()objects - just use the basicfetch()function. - No Headers Class: Headers are plain JavaScript objects, not Header class instances.
- No FormData: Multipart form data isn’t supported - use JSON or URL-encoded strings instead.
- No WebSocket Support: Only HTTP requests work, no WebSocket connections.