Skip to content

Every RN dev hits "Axios Network Error". This tool fixes that by auto-detecting the environment and rewriting your API URLs. It also patches Android/iOS debug configs for cleartext HTTP and optional HTTPS tunneling.

License

Notifications You must be signed in to change notification settings

khokanuzzaman/react-native-dev-proxy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ React Native Dev Proxy

npm version License: MIT Downloads

Automatically detect React Native platform and rewrite API URLs for local development

🎯 The Problem This Solves

When developing React Native apps, you often face this frustrating issue:

// ❌ This works in iOS Simulator but fails on Android device
const response = await fetch('http://localhost:8000/api/users');
// Error: Network request failed

Why does this happen?

  • iOS Simulator can access localhost directly
  • Android Emulator needs 10.0.2.2 instead of localhost
  • Physical devices need your computer's actual IP address
  • Different platforms require different URL configurations

✨ The Solution

react-native-dev-proxy automatically handles URL rewriting for you:

// βœ… This works everywhere - iOS, Android, simulators, and devices
import { withDevProxy } from 'react-native-dev-proxy';
import axios from 'axios';

const api = withDevProxy(axios.create({
  baseURL: 'http://localhost:8000',
}), { strategy: 'auto' });

const users = await api.get('/api/users'); // Works everywhere!

πŸš€ Quick Start

1. Install the Package

npm install react-native-dev-proxy
# or
yarn add react-native-dev-proxy

2. Apply the Patch

npx rn-dev-proxy patch

Apply Patch GIF Running the patch command to configure your React Native project

3. Wrap Your API Client

import { withDevProxy } from 'react-native-dev-proxy';
import axios from 'axios';

const api = withDevProxy(
  axios.create({
    baseURL: 'http://localhost:8000',
    timeout: 10000,
  }),
  {
    strategy: 'auto', // Automatically choose the best method
    log: true,        // Show URL rewriting logs
  }
);

// Now your API calls work everywhere!
const users = await api.get('/api/users');

Code Integration GIF See how easy it is to integrate with your existing code

πŸ“± Platform Support

Platform Original URL Rewritten URL Status
iOS Simulator localhost:8000 localhost:8000 βœ… Works
Android Emulator localhost:8000 10.0.2.2:8000 βœ… Works
Physical iOS Device localhost:8000 192.168.1.100:8000 βœ… Works
Physical Android Device localhost:8000 192.168.1.100:8000 βœ… Works

Platform Support GIF See how the proxy automatically adapts to different platforms

Platform Screenshots

iOS Simulator iOS Simulator working with localhost

Android Emulator Android Emulator working with 10.0.2.2

Physical Device Physical device working with IP address

πŸ› οΈ API Reference

withDevProxy(apiClient, options)

Wraps your API client with automatic URL rewriting.

Parameters:

  • `apiClient: Your API client (axios, fetch, etc.)
  • options: Configuration object

Options:

{
  strategy: 'auto' | 'lan' | 'tunnel', // URL rewriting strategy
  log: boolean,                         // Enable logging
  baseURL: string,                      // Base URL to rewrite
}

makeFetch(options)

Creates a fetch wrapper with automatic URL rewriting.

Parameters:

  • options: Configuration object (same as above)

🎯 Usage Examples

Axios Integration

import { withDevProxy } from 'react-native-dev-proxy';
import axios from 'axios';

const api = withDevProxy(
  axios.create({
    baseURL: 'http://localhost:8000',
    timeout: 10000,
  }),
  { strategy: 'auto', log: true }
);

// All these work automatically on any platform
const users = await api.get('/api/users');
const user = await api.post('/api/users', { name: 'John' });
const updated = await api.put('/api/users/1', { name: 'Jane' });
const deleted = await api.delete('/api/users/1');

Fetch Integration

import { makeFetch } from 'react-native-dev-proxy';

const fetchApi = makeFetch({
  baseURL: 'http://localhost:8000',
  strategy: 'auto',
  log: true,
});

// Works everywhere
const response = await fetchApi('/api/users');
const data = await response.json();

React Hook Example

import { useState, useEffect } from 'react';
import { withDevProxy } from 'react-native-dev-proxy';
import axios from 'axios';

const api = withDevProxy(
  axios.create({ baseURL: 'http://localhost:8000' }),
  { strategy: 'auto', log: true }
);

const useUsers = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await api.get('/api/users');
        setUsers(response.data);
      } catch (error) {
        console.error('Failed to fetch users:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  return { users, loading };
};

πŸ”§ Configuration Options

Strategy Options:

  • auto (recommended): Automatically detects the best method
  • lan: Always uses your computer's IP address
  • tunnel: Uses tunneling service (ngrok, etc.)

Logging:

// Enable detailed logging
const api = withDevProxy(axios, { 
  strategy: 'auto', 
  log: true 
});

// Console output:
// πŸ”§ [DevProxy] Detected platform: android
// πŸ”§ [DevProxy] Using strategy: lan
// πŸ”§ [DevProxy] Rewriting URL: http://localhost:8000/api/users
// πŸ”§ [DevProxy] To: http://192.168.1.100:8000/api/users
// πŸ“‘ [DevProxy] Request successful: 200 OK

πŸ§ͺ Testing Your Setup

Create a simple test component:

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { withDevProxy } from 'react-native-dev-proxy';
import axios from 'axios';

const api = withDevProxy(
  axios.create({ baseURL: 'http://localhost:8000' }),
  { strategy: 'auto', log: true }
);

const TestComponent = () => {
  const [result, setResult] = useState('');

  const testAPI = async () => {
    try {
      const response = await api.get('/api/ping');
      setResult(`βœ… Success: ${JSON.stringify(response.data)}`);
    } catch (error) {
      setResult(`❌ Error: ${error.message}`);
    }
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={testAPI}>
        <Text style={styles.buttonText}>Test API</Text>
      </TouchableOpacity>
      <Text style={styles.result}>{result}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  button: { backgroundColor: '#007AFF', padding: 15, borderRadius: 8 },
  buttonText: { color: 'white', fontWeight: 'bold' },
  result: { marginTop: 20, textAlign: 'center' },
});

export default TestComponent;

Testing Setup GIF Watch the test component in action across different platforms

πŸ”§ Advanced Configuration

Custom Base URL

const api = withDevProxy(axios, {
  baseURL: 'http://localhost:3000', // Your custom server
  strategy: 'auto',
  log: true,
});

Environment-Specific Configuration

const isDevelopment = __DEV__;
const baseURL = isDevelopment 
  ? 'http://localhost:8000' 
  : 'https://api.yourapp.com';

const api = withDevProxy(axios.create({ baseURL }), {
  strategy: isDevelopment ? 'auto' : 'lan',
  log: isDevelopment,
});

πŸ› Troubleshooting

Common Issues:

1. "Network request failed" error:

  • Ensure your server is running on the correct port
  • Check that adb reverse is set up for Android
  • Verify your computer and device are on the same network

2. URLs not being rewritten:

  • Make sure you're using the wrapped API client
  • Check that the patch was applied correctly
  • Verify the baseURL matches your server

3. iOS Simulator issues:

  • Try using 127.0.0.1 instead of localhost
  • Check your server's CORS settings

Debug Steps:

  1. Enable logging:
const api = withDevProxy(axios, { log: true });
  1. Check console output:
πŸ”§ [DevProxy] Detected platform: android
πŸ”§ [DevProxy] Using strategy: lan
πŸ”§ [DevProxy] Rewriting URL: http://localhost:8000/api/users
  1. Test with curl:
curl http://localhost:8000/api/users

Troubleshooting GIF See how to debug and fix common issues

Console Logging

Console Logs Detailed console logging showing URL rewriting

Patch Command Output

Patch Output Patch command successfully configuring your project

Code Editor Integration

Code Editor Easy integration in your code editor

Network Architecture

Network Diagram Visual representation of how the proxy works

Error Handling

Error Handling Comprehensive error handling and debugging

πŸ“š Examples Repository

Check out our examples repository for:

  • Complete React Native app examples
  • Different API client integrations
  • Testing setups
  • Production configurations

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ™ Acknowledgments

  • React Native community for the amazing platform
  • Contributors who helped make this package better
  • All the developers who faced this problem before us

πŸ“ž Support


Made with ❀️ for the React Native community

About

Every RN dev hits "Axios Network Error". This tool fixes that by auto-detecting the environment and rewriting your API URLs. It also patches Android/iOS debug configs for cleartext HTTP and optional HTTPS tunneling.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published