From 690a2fbd51a2b04edad004120356802497a7ed10 Mon Sep 17 00:00:00 2001 From: virtus Date: Fri, 24 Apr 2026 01:30:05 +0700 Subject: [PATCH] Add Next.js instrumentation hook and update HTTP agent options to disable keep-alive for Google OAuth --- instrumentation.ts | 28 ++++++++++++++++++++++++++++ next.config.mjs | 7 +++++++ 2 files changed, 35 insertions(+) create mode 100644 instrumentation.ts diff --git a/instrumentation.ts b/instrumentation.ts new file mode 100644 index 0000000..cd311a3 --- /dev/null +++ b/instrumentation.ts @@ -0,0 +1,28 @@ +/** + * Next.js Instrumentation Hook — chạy một lần khi server khởi động. + * + * Mục đích: + * 1. Ép IPv4-first để tránh Happy Eyeballs timeout khi gọi Google OAuth + * (openid-client bên trong NextAuth gọi oauth2.googleapis.com). + * 2. Tắt keep-alive trên global https agent để tránh stale connection: + * Sau lần đăng nhập đầu, connection pool giữ lại TCP socket tới Google. + * NAT/firewall của Docker drop socket này sau vài phút (silently). + * Khi đăng nhập lần 2, openid-client cố reuse socket đã chết → treo 3500ms. + * keepAlive: false buộc mở connection mới mỗi request, không reuse pool cũ. + */ +export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + const { setDefaultResultOrder } = await import("dns") + setDefaultResultOrder("ipv4first") + + const https = await import("https") + https.globalAgent = new https.Agent({ + keepAlive: false, + }) + + const http = await import("http") + http.globalAgent = new http.Agent({ + keepAlive: false, + }) + } +} diff --git a/next.config.mjs b/next.config.mjs index 040796a..2c699ab 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -3,6 +3,13 @@ const readerApiOrigin = (process.env.READER_API_ORIGIN || "http://localhost:8000 const nextConfig = { output: "standalone", + // Tắt HTTP keep-alive để tránh stale connection tới Google OAuth. + // Sau lần đăng nhập đầu, Node.js giữ TCP socket tới oauth2.googleapis.com trong pool. + // NAT/firewall của Docker drop socket sau vài phút (silently). Khi login lần 2, + // openid-client (bên trong NextAuth) reuse socket đã chết → request treo → OAUTH_CALLBACK_ERROR 3500ms. + httpAgentOptions: { + keepAlive: false, + }, typescript: { ignoreBuildErrors: true, },