const { createServer } = require("node:http"); const { readFile } = require("node:fs/promises"); const { join } = require("node:path"); const port = Number(process.env.PORT || 8080); const backendUrl = process.env.BE_URL || "http://be:8080/api/hello"; function sendJson(response, status, body) { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }); response.end(JSON.stringify(body)); } const server = createServer(async (request, response) => { const pathname = new URL(request.url || "/", "http://localhost").pathname; if (request.method === "GET" && pathname === "/health") { return sendJson(response, 200, { status: "ok", service: "fe" }); } if (request.method === "GET" && pathname === "/api/hello") { try { const backendResponse = await fetch(backendUrl, { signal: AbortSignal.timeout(3000) }); const body = await backendResponse.text(); response.writeHead(backendResponse.status, { "content-type": backendResponse.headers.get("content-type") || "application/json; charset=utf-8", }); return response.end(body); } catch { return sendJson(response, 502, { error: "Backend is unavailable", backendUrl }); } } if (request.method === "GET" && pathname === "/") { try { const html = await readFile(join(__dirname, "index.html")); response.writeHead(200, { "content-type": "text/html; charset=utf-8" }); return response.end(html); } catch { return sendJson(response, 500, { error: "Frontend page is unavailable" }); } } return sendJson(response, 404, { error: "Not found" }); }); server.listen(port, "0.0.0.0", () => { console.log(`FE listening on port ${port}`); });