Repository navigation
Description
getEnv reads the host's second entry argument from one module-level variable, platformEnv, which seedContext overwrites on every entry call (runtime.ts#L58, #L75-L79, #L166-L171). The doc comment explains why this is fine on Cloudflare Workers: the bindings object is the same for every request in an isolate. On other hosts the second argument belongs to one request, and then the last entry call decides what every in-flight request reads.
Reproduction
@supabase/middleware at main (dc7d9fb, 1.0.0), Node 24:
import { defineMiddleware, getEnv } from "@supabase/middleware";
const seen = [];
const withTenant = defineMiddleware({
key: "tenant",
run: () => async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
return { tenant: getEnv("TENANT") };
},
});
const app = withTenant(async (_req, ctx) => {
seen.push(ctx.tenant);
return new Response("ok");
});
await Promise.all([
app(new Request("https://a.test/1"), { TENANT: "one" }),
app(new Request("https://a.test/2"), { TENANT: "two" }),
]);
console.log(seen); // [ 'two', 'two' ]The first request reads the second request's object.
How much it matters
I want to be plain about the size of this. I have not found a production host where two requests get different bindings objects with the same key, so I know of no wrong value being served today. What does happen:
- Any object in second position becomes "the env": a Next.js
proxyevent (getEnv("sourcePage")returns/proxyin a Next.js 16.5.0 app, see Honor the WorkersExecutionContext(waitUntil) instead of dropping it #53 (comment)), a Next.js route handler's{ params }, a DenoServeHandlerInfo. A string field on such an object shadows a real environment variable of the same name. - The last request's object stays referenced by the module until the next entry call.
- Tests and embedding hosts that pass different bindings per call (two tenants, two fixtures) read whichever call came last, as in the reproduction.
Proposal
Keep the second argument on the seeded context as well, behind a Symbol.for key like the context marker, and let getEnv take the context as an optional second argument:
getEnv("SUPABASE_DB_URL", ctx); // this request's bindings, then the host env
getEnv("SUPABASE_DB_URL"); // unchanged: the module-level slot, then the host envCode that has a ctx (every middleware run and every handler) can then read its own request's bindings, and nothing changes for callers that pass no context. #65 keeps the execution context on the seeded context the same way, for the same reason.
I have not sent a PR for this one. It adds to the public API, and #65, #68 and #69 already edit seedContext and getEnv, so I would rather hear whether you want it before adding a fourth change to the same lines. I'm happy to write it.
Activity