React Native HTTP Bridge Refurbished

1.2.9 · active · verified Wed Apr 22

The `react-native-http-bridge-refurbished` package provides a lightweight, in-app HTTP server designed for debugging React Native applications. It allows developers to expose an HTTP endpoint directly from their mobile app, facilitating interaction, data inspection, and remote control for development purposes. Currently stable at version `1.3.2`, the project sees sporadic but active maintenance, with recent updates addressing bug fixes and minor feature enhancements, such as improved URL parameter handling. As a 'refurbished' version of an earlier, potentially unmaintained library, its key differentiator is its continued support and compatibility with modern React Native versions (requiring `>=0.72`), offering a robust alternative for in-app web server functionalities.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates starting an HTTP debug server within a React Native app, registering two GET routes (`/` and `/echo`), and handling incoming requests to provide a basic JSON or text response. It also shows how to stop the server and displays the last received request.

import React, { useEffect, useState } from 'react';
import { View, Text, Button, Alert, StyleSheet } from 'react-native';
import { HttpBridge, type HttpRequest } from 'react-native-http-bridge-refurbished';

const SERVER_PORT = 8080;

const App: React.FC = () => {
  const [serverStatus, setServerStatus] = useState('Stopped');
  const [lastRequest, setLastRequest] = useState<HttpRequest | null>(null);

  useEffect(() => {
    // Start the HTTP server
    HttpBridge.start(SERVER_PORT, true); // true enables console logging
    setServerStatus(`Running on port ${SERVER_PORT}`);

    // Register a request handler
    HttpBridge.onHttpRequest((request: HttpRequest) => {
      console.log('Received HTTP Request:', request);
      setLastRequest(request);

      if (request.url === '/') {
        HttpBridge.respond(
          request.requestId,
          200,
          'application/json',
          JSON.stringify({ message: 'Hello from React Native HTTP Bridge!' })
        );
      } else if (request.url.startsWith('/echo')) {
        const urlObj = new URL(`http://localhost${request.url}`); // Use a dummy base URL to parse parameters
        const echoMessage = urlObj.searchParams.get('message') || 'No message provided';
        HttpBridge.respond(
           request.requestId,
           200,
           'text/plain',
           `Echo: ${echoMessage}`
        );
      } else {
        HttpBridge.respond(
          request.requestId,
          404,
          'text/plain',
          'Not Found: Try / or /echo?message=your_text'
        );
      }
    });

    // Cleanup on component unmount
    return () => {
      HttpBridge.stop();
      setServerStatus('Stopped');
      console.log('HTTP Bridge server stopped.');
    };
  }, []);

  const handleStopServer = () => {
    HttpBridge.stop();
    setServerStatus('Stopped');
    Alert.alert('Server Stopped', `HTTP server on port ${SERVER_PORT} has been stopped.`);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>HTTP Debug Server</Text>
      <Text style={styles.statusText}>Status: {serverStatus}</Text>
      <Button title="Stop Server" onPress={handleStopServer} />
      {lastRequest && (
        <View style={styles.requestBox}>
          <Text style={styles.requestHeader}>Last Request:</Text>
          <Text>Method: {lastRequest.method}</Text>
          <Text>URL: {lastRequest.url}</Text>
          <Text numberOfLines={1}>Headers: {JSON.stringify(lastRequest.headers)}</Text>
          <Text numberOfLines={1}>Body: {lastRequest.body || '(empty)'}</Text>
        </View>
      )}
      <Text style={styles.instructions}>
        Access from browser/client (use your device's IP):
        `http://[YOUR_DEVICE_IP]:${SERVER_PORT}/`
        `http://[YOUR_DEVICE_IP]:${SERVER_PORT}/echo?message=Hello`
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#f8f8f8',
  },
  title: {
    fontSize: 26,
    fontWeight: 'bold',
    marginBottom: 15,
    color: '#333',
  },
  statusText: {
    fontSize: 18,
    marginBottom: 25,
    color: '#555',
  },
  requestBox: {
    marginTop: 30,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 15,
    width: '100%',
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  requestHeader: {
    fontWeight: 'bold',
    fontSize: 16,
    marginBottom: 5,
    color: '#333',
  },
  instructions: {
    marginTop: 30,
    fontSize: 14,
    textAlign: 'center',
    color: '#777',
    lineHeight: 20,
  },
});

export default App;

view raw JSON →