From e9dfc89b410be9dc2438a0102d8a2611a6988bae Mon Sep 17 00:00:00 2001 From: Etienne Samson Date: Fri, 21 Aug 2026 06:27:50 +0200 Subject: [PATCH] Fix ERR_HTTP_HEADERS_ALREADY_SENT errors that pop up in the logs --- lib/backend/api/index.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/lib/backend/api/index.js b/lib/backend/api/index.js index edb4aa4..093cdb2 100755 --- a/lib/backend/api/index.js +++ b/lib/backend/api/index.js @@ -6,6 +6,29 @@ const auth = require('@screeps/backend/lib/game/api/auth') const authlib = require('@screeps/backend/lib/authlib') const _ = require('lodash') +/** + * Like legacy `q-json-response`, envelopes success as `{ ok: 1, ...data }`. + * Unlike it, does NOT call next() after responding: our routes shadow vanilla + * backend routes at the same paths, and falling through would execute the + * vanilla handler on an already-answered request (double side effects, and + * ERR_HTTP_HEADERS_SENT crashes in its tokenAuth). + */ +function jsonResponse (fn) { + return function (request, response) { + Promise.resolve() + .then(() => fn(request, response)) + .then((data) => { + response.json(_.extend({ ok: 1 }, data)) + }) + .catch((error) => { + if (error.stack) console.error(error.stack) + if (!response.headersSent) { + response.json({ error: String(error) }) + } + }) + } +} + module.exports = function (config) { const { common } = config const { db, env, pubsub } = common.storage