async createContext for Express Adapter
Been debugging an odd behavior for the past hour, it seems like that an async function does not work in the express adapter. Is that supposed to work or is that the expected behavior? If this is a bug i can toss together a quick sandbox, but figured I check first whether this is expected or not.
If this is expected behavior, should the async calls happen in middleware instead? Seems a bit at odds. Thoughts?
3 Replies
// Works
router.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext: () => { user: 'test' },
}),
);
// Does not work, user is always undefined
router.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext: () => someAsyncFunction();
}),
);
It’s worth putting together a reproduction, chances are it’s a mistake in your code, but if it’s reproducible then definitely raise a bug ticket on GitHub
Yeah, can't seem to reproduce in the code sandbox. Will have to dig some more into it. Speaking of codesandbox, I couldn't get the express example to work at all initially, adding node-fetch polyfill seems to fix it though: https://codesandbox.io/s/sleepy-booth-rl1xqk?file=/src/client.ts
import fetch from "node-fetch";
// @ts-ignore
globalThis.fetch = fetch;
I'll open a pr for it later
Just for completion sake... I was sure it had something to do with CORS i kept seeing undefined context and then delayed the correct context. Async didn t work, sync worked...
The context code was something like this:
() => {
// do a bunch of stuff
someFunction(() => {
return { user }; } return { user: undefined}; } tl;dr => there was another return path in the context from some earlier testing. Both returns would trigger eventually. but the initially one was the undefined, later on the internal function returned again haha
return { user }; } return { user: undefined}; } tl;dr => there was another return path in the context from some earlier testing. Both returns would trigger eventually. but the initially one was the undefined, later on the internal function returned again haha