-
Using next.js 14 pages router: I've run into an issue where I want to use prefetchQuery on a dashboard page that querying a couple API's that have next-auth session checks. These queries are setup using query-key-factory and I tried using a fetch request instead of the axios query and still got the same issue. import { GetServerSideProps } from 'next';
import { getServerSession } from 'next-auth/next';
import { QueryClient, dehydrate } from '@tanstack/react-query';
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const queryClient = new QueryClient();
const session = await getServerSession(ctx.req, ctx.res, authOptions);
// next-auth cookies included in request header
console.log('SERVER DASH HEADERS', ctx.req.headers);
if (session) {
await Promise.all([
// sends GET request to /api/tasks/latest
queryClient.prefetchQuery(queries.tasks.latestConfirmed),
queryClient.prefetchQuery(queries.users.stats(session?.user.id as string)),
]);
}
const extraProps = {
session,
dehydratedState: dehydrate(queryClient),
};
return await checkUserSessionProtected(ctx, extraProps, session);
}; When However, on the client-side when using Is there no way to have prefetchQuery include the cookie in the request? // api/tasks/latest
// called by prefetchQuery and useQuery
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
switch (req.method) {
case 'GET':
try {
// req.headers does not include cookie when called with prefetchQuery
const session = await getServerSession(req, res, authOptions);
if (!session) {
return res.status(401).json({ error: 'You must be authenticated. Please sign in.' });
}
....
} catch (err) {
return res.status(500).json({ error: 'Error finding tasks' });
}
default:
res.status(405).send({ error: 'Method not allowed' });
break;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
prefetchQuery just runs the queryFn you pass to it. React Query doesn't know or care about requests / headers or anything like that. So if there's something missing, it must be because of how the queryFn is implemented. |
Beta Was this translation helpful? Give feedback.
I figured it out, I added
withCredentials
to the axios instance then passed the cookie to the request on server side.It now passes the cookie with the request from the server to API route.