Skip to content

Instantly share code, notes, and snippets.

@zabirauf
Created March 19, 2024 15:02
Show Gist options
  • Save zabirauf/c9765b4290d3ff86eaa764fb0bf6cfbf to your computer and use it in GitHub Desktop.
Save zabirauf/c9765b4290d3ff86eaa764fb0bf6cfbf to your computer and use it in GitHub Desktop.
Claude proxy service to support CORS
import { serve } from 'https://deno.land/[email protected]/http/server.ts';
const PORT = 8088;
const ALLOWED_HEADERS = ['x-api-key', 'anthropic-version', 'Content-Type'];
function addCORSHeaders(responseHeaders: Headers) {
responseHeaders.set('Access-Control-Allow-Origin', '*'); // Allow requests from any origin
responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // Allowed methods
responseHeaders.set('Access-Control-Allow-Headers', '*'); // Allow all headers
}
const handleRequest = async (request: Request): Promise<Response> => {
if (request.method == 'OPTIONS') {
console.log('Received OPTIONS request');
// Add CORS headers
const responseHeaders = new Headers();
addCORSHeaders(responseHeaders);
return new Response(null, {
status: 200,
headers: responseHeaders,
});
}
const targetURL = request.headers.get('x-url');
console.log('Received request', targetURL);
if (!targetURL) {
return new Response("Please provide an 'x-url' header.", { status: 400 });
}
const requestHeaders = new Headers();
for (const [key, value] of request.headers.entries()) {
if (ALLOWED_HEADERS.includes(key.toLowerCase())) {
requestHeaders.set(key, value);
}
}
const requestBody = request.body ? await request.arrayBuffer() : undefined;
const proxyRequest = new Request(targetURL, {
method: request.method,
headers: requestHeaders,
body: requestBody,
});
const proxyResponse = await fetch(proxyRequest);
const responseHeaders = new Headers(proxyResponse.headers);
const responseBody = proxyResponse.body;
// Add CORS headers
addCORSHeaders(responseHeaders);
return new Response(responseBody, {
status: proxyResponse.status,
headers: responseHeaders,
});
};
console.log(`Proxy server listening on http://localhost:${PORT}`);
await serve(handleRequest, { port: PORT });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment