I'm developping an application with a Next, TRPC and NextAuth (and Prisma but I believe there no issue with that one).
I have a page which displays a collection of elements. It retrieves the collection via an authenticated TRPC useQuery :
function Collection() {
const { data: session } = useSession();
const collectionsQuery = trpc.collectionRouter.collection.useQuery();
if (session) {
return (
<div>
<Layout>
<h1>Collections</h1>
<Link href="/collections/add" className="btn btn-sm btn-success mb-2">Add Collection</Link>
<div>
{
collectionsQuery.data && collectionsQuery.data.length != 0 ?
JSON.stringify(collectionsQuery.data)
:
<div className="p-2">No collections To Display</div>
}
</div>
</Layout>
</div>
);
} else {
return (
<div>Not logged</div>
)
}
}
It always fail when I reload the page, then when I navigate via my application menu to go to another page and come back to this page, all queries are successfull.
On server side (context,ts), the getSession returns null on reload page, then works on every further calls :
export async function createContext(opts: trpcNext.CreateNextContextOptions) {
const session = await getSession(opts);
if (session == null) {
console.log("null session");
}
return {
session,
};
};
What could cause the session to be null on page reload ?
Edit : When the query does not work on page reload, I see that the auth cookie is correctly set client side but is null on server side.
Edit 2 : This seems related to this one Don't get cookies in trpc context But the advice of including the following piece of code in createTRPCNext / config does not work and does not even seem to get called :
headers: () => {
if (ctx?.req) {
// on ssr, forward client's headers to the server
return {
...ctx.req.headers,
'x-ssr': '1',
};
}