Recently, I've been setting up TRPC with Next.js and attempting to implement server-side rendering where I fetch user data before the page loads using the trpc.useQuery hook. However, I'm facing an issue where I cannot access the JWT token cookie in the trpc context.
Here is a snippet of the code from my [username].tsx page:
const UserPage: NextPage = () => {
const router = useRouter();
const username = router.query.username as string;
const user = trpc.useQuery([
"user.by-username",
{
username,
},
]);
return <Text>{user?.data?.id}</Text>;
};
export default UserPage;
Additionally, here's a section of the code from the trpc context where I encounter difficulty accessing the cookies:
export const createContext = (opts?: trpcNext.CreateNextContextOptions) => {
const req = opts?.req;
const res = opts?.res;
console.log(req?.cookies) // Unable to retrieve cookies at this point
const user = jwt.verify(req?.cookies.token as string, process.env.JWT_SECRET as string) as User
return {
req,
res,
prisma,
user
};
};
type Context = trpc.inferAsyncReturnType<typeof createContext>;
export const createRouter = () => trpc.router<Context>();