How to invalidate trpc queries in Next13
The code speaks for itself. I want to invalidate a trpc query in a server action but I get a super weird error. (I know I can do it with state and client component). Is there a way to do that in the server action ?
Error: Unhandled Runtime Error
Error: invalid json response body at http://localhost:3000/api/trpc/user.myName,post.getLatest?batch=1&input=%7B%220%22%3A%7B%22json%22%3Anull%2C%22meta%22%3A%7B%22values%22%3A%5B%22undefined%22%5D%7D%7D%2C%221%22%3A%7B%22json%22%3Anull%2C%22meta%22%3A%7B%22values%22%3A%5B%22undefined%22%5D%7D%7D%7D reason: Unexpected token I in JSON at position 0
6 Replies
i think this is due to "bad" header forwarding. do you forward every header? iirc it has something to do with the transfer encoding header
Good point, this is how I configure my trpc client:
"use server";
import { getUrl, transformer } from "./shared";
import { httpBatchLink, httpLink, loggerLink, splitLink } from "@trpc/client";
import { experimental_createTRPCNextAppDirServer } from "@trpc/next/app-dir/server";
import { headers } from "next/headers";
import { type AppRouter } from "~/server/api/root";
import fetchPonyfill from "fetch-ponyfill";
export const api = experimental_createTRPCNextAppDirServer<AppRouter>({
config() {
return {
transformer,
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
splitLink({
condition(op) {
// check for context property
skipBatch
return op.context.skipBatch === true;
},
// when condition is true, use normal request
true: httpLink({
// vercel issue with fetch undici
fetch: fetchPonyfill().fetch,
url: getUrl(),
}),
// when condition is false, use batching
false: httpBatchLink({
fetch: fetchPonyfill().fetch,
url: getUrl(),
headers() {
// Forward headers from the browser to the API
return {
...Object.fromEntries(headers()),
"x-trpc-source": "rsc",
};
},
}),
}),
],
};
},
});
the relevant part regarding your suggestion: headers() {
// Forward headers from the browser to the API
return {
...Object.fromEntries(headers()),
"x-trpc-source": "rsc",
};
},
Do you think the forwarded headers are correct?test
that worked!! thanks a lot! ... I'm curious, how did you know and where can I learn more about this topic ? 😄
and how can I mark your answer as the answer to this question 😄
i ran into this issue a bit back and nailed the issue down to the streaming release and went from there 😅 wasn't fun debuggin that one
I also tried but I wasn't able to nailed it. I'm impressed 😄 thanks a lot!