From c2b36cdffaa0b418bc22588c637f5fcde6fc9ef5 Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Sun, 21 May 2023 00:06:28 +0800 Subject: [PATCH] feat: prevent browser to invoke basic auth popup --- app/api/common.ts | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/app/api/common.ts b/app/api/common.ts index eb073922..b606d8ca 100644 --- a/app/api/common.ts +++ b/app/api/common.ts @@ -30,26 +30,30 @@ export async function requestOpenai(req: NextRequest) { controller.abort(); }, 10 * 60 * 1000); + const fetchUrl = `${baseUrl}/${openaiPath}`; + const fetchOptions: RequestInit = { + headers: { + "Content-Type": "application/json", + Authorization: authValue, + ...(process.env.OPENAI_ORG_ID && { + "OpenAI-Organization": process.env.OPENAI_ORG_ID, + }), + }, + cache: "no-store", + method: req.method, + body: req.body, + signal: controller.signal, + }; + try { - return await fetch(`${baseUrl}/${openaiPath}`, { - headers: { - "Content-Type": "application/json", - Authorization: authValue, - ...(process.env.OPENAI_ORG_ID && { - "OpenAI-Organization": process.env.OPENAI_ORG_ID, - }), - }, - cache: "no-store", - method: req.method, - body: req.body, - signal: controller.signal, - }); - } catch (err: unknown) { - if (err instanceof Error && err.name === "AbortError") { - console.log("Fetch aborted"); - } else { - throw err; + const res = await fetch(fetchUrl, fetchOptions); + + if (res.status === 401) { + // to prevent browser prompt for credentials + res.headers.delete("www-authenticate"); } + + return res; } finally { clearTimeout(timeoutId); }