pvman
pvman7mo ago

> Error: Invariant: headers() expects to have requestAsyncStorage, none available

Hi, I use trpc v1045.1 in next 14.1 app router. I call it server side and have the following.
export async function createContext(opts: CreateNextContextOptions) {
const { session, user } = await getUserAuth();

return {
db,
session,
user,
...opts,
};
};

export const createServerApi = cache(async () => {
const heads = new Headers(headers());
heads.set("x-trpc-source", "rsc");

const context = await createTRPCContext({
headers: heads,
});

return createCaller(context);
});

export const api = await createServerApi();
export async function createContext(opts: CreateNextContextOptions) {
const { session, user } = await getUserAuth();

return {
db,
session,
user,
...opts,
};
};

export const createServerApi = cache(async () => {
const heads = new Headers(headers());
heads.set("x-trpc-source", "rsc");

const context = await createTRPCContext({
headers: heads,
});

return createCaller(context);
});

export const api = await createServerApi();
It is working on a static route but on a dynamic route /edit/[slug] I get the following error (coming from the headers() in createServerApi):
Error: Invariant: headers() expects to have requestAsyncStorage, none available
Any idea how I could solve this?
4 Replies
BeBoRE
BeBoRE7mo ago
You need to call createServerApi from within your server component, you are currently calling headers() outside of Next
pvman
pvman7mo ago
Oh ok, but why is it working for static route? So no way to have a single function to call in the server ? I have to do :
const api = await createServerApi();
const post = await api.posts.getPostById(slug);

const api = await createServerApi();
const post = await api.posts.getPostById(slug);

But would like to only have to do : const post = await api.posts.getPostById(slug);
BeBoRE
BeBoRE7mo ago
You can do that in v11 not in v10. In v10 you’ll have to use this pattern, or you’d have to use a proxy probably
pvman
pvman7mo ago
Thanks a lot for the clarification and for helping @BeBoRE , really appreciate!