capacitor-cors-proxy
v2.0.2
Published
A Capacitor plugin to solve CORS issues for HTTP requests and SSE connections
Maintainers
Readme
capacitor-cors-proxy
A Capacitor plugin to solve CORS issues for HTTP requests and SSE connections by using native HTTP clients.
Features
- ✅ HTTP requests bypassing CORS restrictions
- ✅ Server-Sent Events (SSE) support with automatic reconnection
- ✅ WebSocket connections bypassing CORS
- ✅ Complete MCP (Model Context Protocol) support
- ✅ Custom headers support
- ✅ Automatic retry mechanisms
- ✅ Cross-platform support (iOS, Android, Web)
Install
npm install capacitor-cors-proxy
npx cap syncUsage
HTTP Requests
import { CorsProxy } from 'capacitor-cors-proxy';
// Simple GET request
const response = await CorsProxy.request({
url: 'https://api.example.com/data',
method: 'GET',
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
}
});
console.log('Response:', response.data);
// POST request with data
const postResponse = await CorsProxy.request({
url: 'https://api.example.com/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: {
name: 'John Doe',
email: '[email protected]'
}
});Server-Sent Events (SSE)
import { CorsProxy } from 'capacitor-cors-proxy';
// Create SSE connection
const sseConnection = await CorsProxy.createSSEConnection({
url: 'https://api.example.com/events',
headers: {
'Authorization': 'Bearer your-token'
},
reconnect: {
enabled: true,
initialDelay: 1000,
maxDelay: 30000,
maxAttempts: 10
}
});
// Listen for SSE messages
CorsProxy.addListener('sseMessage', (event) => {
console.log('SSE Message:', event);
// event.connectionId, event.type, event.data, event.id, event.retry
});
// Listen for connection status changes
CorsProxy.addListener('sseConnectionChange', (event) => {
console.log('SSE Connection Status:', event.status);
// event.connectionId, event.status, event.error
});
// Close connection when done
await CorsProxy.closeSSEConnection({
connectionId: sseConnection.connectionId
});WebSocket Connections
import { CorsProxy } from 'capacitor-cors-proxy';
// Create WebSocket connection
const wsConnection = await CorsProxy.createWebSocketConnection({
url: 'wss://api.example.com/websocket',
protocols: ['chat', 'superchat'],
headers: {
'Authorization': 'Bearer your-token'
},
timeout: 10000
});
// Listen for WebSocket messages
CorsProxy.addListener('webSocketMessage', (event) => {
console.log('WebSocket Message:', event);
// event.connectionId, event.data, event.type
});
// Listen for connection status changes
CorsProxy.addListener('webSocketConnectionChange', (event) => {
console.log('WebSocket Status:', event.status);
// event.connectionId, event.status, event.error
});
// Send message
await CorsProxy.sendWebSocketMessage({
connectionId: wsConnection.connectionId,
message: JSON.stringify({ type: 'chat', content: 'Hello!' })
});
// Close connection
await CorsProxy.closeWebSocketConnection({
connectionId: wsConnection.connectionId
});MCP (Model Context Protocol) Support
import { CorsProxy } from 'capacitor-cors-proxy';
// Create MCP client with full protocol support
const mcpClient = await CorsProxy.createMCPClient({
sseUrl: 'https://your-mcp-server.com/sse',
postUrl: 'https://your-mcp-server.com/messages',
clientInfo: {
name: 'your-app',
version: '1.0.0'
},
capabilities: {
sampling: true,
roots: { listChanged: true }
}
});
// List available resources
const resources = await CorsProxy.listMCPResources({
connectionId: mcpClient.connectionId
});
// Read a specific resource
const resource = await CorsProxy.readMCPResource({
connectionId: mcpClient.connectionId,
uri: 'file://example.txt'
});
// List available tools
const tools = await CorsProxy.listMCPTools({
connectionId: mcpClient.connectionId
});
// Call a tool
const result = await CorsProxy.callMCPTool({
connectionId: mcpClient.connectionId,
name: 'search',
arguments: { query: 'example' }
});
// List prompts
const prompts = await CorsProxy.listMCPPrompts({
connectionId: mcpClient.connectionId
});
// Get a prompt
const prompt = await CorsProxy.getMCPPrompt({
connectionId: mcpClient.connectionId,
name: 'summarize',
arguments: { text: 'content to summarize' }
});
// Send sampling request
const samplingResponse = await CorsProxy.sendMCPSampling({
connectionId: mcpClient.connectionId,
request: {
method: 'sampling/createMessage',
params: {
messages: [{
role: 'user',
content: { type: 'text', text: 'Hello!' }
}],
maxTokens: 100
}
}
});API
request(options: HttpRequestOptions)
Make an HTTP request bypassing CORS restrictions.
Parameters:
url(string): The URL to requestmethod(string, optional): HTTP method (default: 'GET')headers(object, optional): Request headersdata(any, optional): Request body for POST/PUT/PATCHparams(object, optional): Query parameterstimeout(number, optional): Request timeout in milliseconds (default: 30000)responseType(string, optional): Response type - 'json', 'text', 'blob', 'arraybuffer' (default: 'json')followRedirects(boolean, optional): Whether to follow redirects (default: true)maxRedirects(number, optional): Maximum redirects to follow (default: 5)
Returns: Promise<HttpResponse>
createSSEConnection(options: SSEConnectionOptions)
Create a Server-Sent Events connection.
Parameters:
url(string): The SSE endpoint URLheaders(object, optional): Request headersreconnect(object, optional): Reconnection optionsenabled(boolean): Auto-reconnect enabled (default: true)initialDelay(number): Initial retry delay in ms (default: 1000)maxDelay(number): Maximum retry delay in ms (default: 30000)maxAttempts(number): Maximum retry attempts (default: 10)
Returns: Promise<SSEConnection>
createWebSocketConnection(options: WebSocketConnectionOptions)
Create a WebSocket connection bypassing CORS.
Parameters:
url(string): The WebSocket URLprotocols(string[], optional): WebSocket protocolsheaders(object, optional): Request headerstimeout(number, optional): Connection timeout in ms (default: 10000)
Returns: Promise<WebSocketConnection>
Events
SSE Events
sseMessage: Fired when an SSE message is receivedsseConnectionChange: Fired when SSE connection status changes
WebSocket Events
webSocketMessage: Fired when a WebSocket message is receivedwebSocketConnectionChange: Fired when WebSocket connection status changes
Platform Support
| Platform | HTTP Requests | SSE | WebSocket | |----------|---------------|-----|-----------| | iOS | ✅ | ✅ | ✅ | | Android | ✅ | ✅ | ✅ | | Web | ✅ | ✅ | ✅ |
Why This Plugin?
Web browsers enforce CORS (Cross-Origin Resource Sharing) policies that can block requests to different domains. This plugin bypasses these restrictions by using native HTTP clients on mobile platforms.
Benefits:
- No CORS Issues: Native HTTP clients don't enforce CORS policies
- Better Performance: Native implementations are often faster
- Advanced Features: Support for SSE and WebSocket with automatic reconnection
- Unified API: Same interface across all platforms
License
MIT
