Skip to content

Instantly share code, notes, and snippets.

@thuykaka
Last active June 6, 2025 02:23
Show Gist options
  • Select an option

  • Save thuykaka/47fc67b63f9ff41e7897773d1ca4989b to your computer and use it in GitHub Desktop.

Select an option

Save thuykaka/47fc67b63f9ff41e7897773d1ca4989b to your computer and use it in GitHub Desktop.
// Telegram Bot API base URL
const TELEGRAM_API_BASE = 'https://api.telegram.org';
async function handleRequest(request) {
const url = new URL(request.url);
// Reconstruct the Telegram API URL
const telegramUrl = `${TELEGRAM_API_BASE}${url.pathname}${url.search}`;
// Create headers for the new request
const headers = new Headers(request.headers);
// Forward the request to Telegram API
let body = undefined;
if (request.method !== 'GET' && request.method !== 'HEAD') {
try {
body = await request.arrayBuffer();
} catch (err) {
return new Response(`Failed to read request body: ${err.message}`, { status: 400 });
}
}
const proxyReq = new Request(telegramUrl, {
method: request.method,
headers: request.headers,
body,
redirect: 'follow',
});
try {
const tgRes = await fetch(proxyReq);
const res = new Response(tgRes.body, tgRes); // Copy response as-is
res.headers.set('Access-Control-Allow-Origin', '*');
res.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.headers.set('Access-Control-Allow-Headers', 'Content-Type');
return res;
} catch (err) {
return new Response(`Error proxying request: ${err.message}`, { status: 500 });
}
}
// Handle OPTIONS requests for CORS
function handleOptions(request) {
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
};
return new Response(null, {
status: 204,
headers: corsHeaders,
});
}
// Main event listener for the worker
addEventListener('fetch', event => {
const request = event.request;
// Handle CORS preflight requests
if (request.method === 'OPTIONS') {
event.respondWith(handleOptions(request));
} else {
event.respondWith(handleRequest(request));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment