postgres.patch1.1 KBView on GitHub

154 error spans on 0 routes in the last 7 days.

diff --git a/src/connection.js b/src/connection.js
index 97cc97e1576d6c75f958c66e9cecbf8cd11ed450..db5456c8c2109d9231a64361a14de48e9671e698 100644
--- a/src/connection.js
+++ b/src/connection.js
@@ -247,9 +247,20 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
   }
 
   function nextWrite(fn) {
-    const x = socket.write(chunk, fn)
     nextWriteTimer !== null && clearImmediate(nextWriteTimer)
-    chunk = nextWriteTimer = null
+    nextWriteTimer = null
+    // socket can become null between write() scheduling this via setImmediate
+    // and this callback running, if the connection closes in that window (e.g.
+    // a pooler like Supabase's closing an idle connection server-side) — without
+    // this guard, socket.write() throws on the null socket and crashes the
+    // whole process instead of the write simply failing like it would have if
+    // the connection had already been closed when write() was first called.
+    if (!socket) {
+      chunk = null
+      return false
+    }
+    const x = socket.write(chunk, fn)
+    chunk = null
     return x
   }