T
tRPC

useMutation throwing 500 errors

useMutation throwing 500 errors

LLiltripple_reid9/4/2023
I've setup my next 13 app router project and started using some queries that worked fine, however the only route I have for mutations fails without any detailed error. I'm using the createTRPCReact with a custom client for RSC.
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink } from "@trpc/client";
import { useState, type ReactNode } from "react";
import superjson from "superjson";
import { apiRSC } from "~/utils/api";

/**
*
* @description should be updated when trpc releases an RSC and Edge compatible version
*
*/
export const TRPCProvider = ({ children }: { children: ReactNode }) => {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
apiRSC.createClient({
links: [
httpBatchLink({
url: "http://localhost:3000/api/trpc",
}),
],
transformer: superjson,
})
);

return (
<apiRSC.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</apiRSC.Provider>
);
};
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink } from "@trpc/client";
import { useState, type ReactNode } from "react";
import superjson from "superjson";
import { apiRSC } from "~/utils/api";

/**
*
* @description should be updated when trpc releases an RSC and Edge compatible version
*
*/
export const TRPCProvider = ({ children }: { children: ReactNode }) => {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
apiRSC.createClient({
links: [
httpBatchLink({
url: "http://localhost:3000/api/trpc",
}),
],
transformer: superjson,
})
);

return (
<apiRSC.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</apiRSC.Provider>
);
};
my trpc-client creator
export const apiRSC = createTRPCReact<AppRouter>();
export const apiRSC = createTRPCReact<AppRouter>();
No description
No description
LLiltripple_reid9/4/2023
traced back the error down to httpUtils as shown in the first screenshot full error thrown from
useMutation({
onError: ...
})
useMutation({
onError: ...
})
TRPCClientError: Unexpected end of JSON input
at TRPCClientError.from (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@trpc+client@10.38.1_@trpc+server@10.38.1/node_modules/@trpc/client/dist/TRPCClientError-fef6cf44.mjs:30:16)
at eval (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@trpc+client@10.38.1_@trpc+server@10.38.1/node_modules/@trpc/client/dist/httpUtils-ad76b802.mjs:136:81)
TRPCClientError: Unexpected end of JSON input
at TRPCClientError.from (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@trpc+client@10.38.1_@trpc+server@10.38.1/node_modules/@trpc/client/dist/TRPCClientError-fef6cf44.mjs:30:16)
at eval (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@trpc+client@10.38.1_@trpc+server@10.38.1/node_modules/@trpc/client/dist/httpUtils-ad76b802.mjs:136:81)
Jjuico9/4/2023
Same error for me
LLiltripple_reid9/4/2023
totally blocked by this tbh okay after digging more into this I think I found the issue, probably the return data of the router mutation isn't being sent as Response, just tried it on a standalone api route handler and this works: so a) it's not my db, b) probably the adapter used is not parsing the responses?
export const POST = async (req: Request) => {
const body = (await req.json()) as unknown;
const parsed = userPickedSchema.safeParse(body);

const session = await getServerSession(authOptions);

if (!session?.user) {
return new TRPCError({
code: "UNAUTHORIZED",
message: "Unauthorized",
});
}

if (!parsed.success) {
return new TRPCError({
code: "BAD_REQUEST",
message: "Invalid body",
});
}

const { user } = session;

const data = await db.update(users).set(parsed.data).where(eq(users.id, user.id));

console.log({ data, parsed, body });

return new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
};
export const POST = async (req: Request) => {
const body = (await req.json()) as unknown;
const parsed = userPickedSchema.safeParse(body);

const session = await getServerSession(authOptions);

if (!session?.user) {
return new TRPCError({
code: "UNAUTHORIZED",
message: "Unauthorized",
});
}

if (!parsed.success) {
return new TRPCError({
code: "BAD_REQUEST",
message: "Invalid body",
});
}

const { user } = session;

const data = await db.update(users).set(parsed.data).where(eq(users.id, user.id));

console.log({ data, parsed, body });

return new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
};
Jjuico9/5/2023
Hmm, still having the same error :/ But now I'm having it on GET() as well: Error: Attempted to call GET() from the server but GET is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.
LLiltripple_reid9/6/2023
wait that's weird are you using app/api/<your_route_name>/route.ts or with trpc app/api/trpc/[trpc]/route.ts?
Jjuico9/11/2023
The second one: app/api/trpc/[trpc]/route.ts? It's resolved, for some reason I was having "use client" at the top of my file. For the life of me I have no idea why I had it there.

Looking for more? Join the community!

T
tRPC

useMutation throwing 500 errors

Join Server
Recommended Posts
TRPC Nextjs App Router API Base URLIs there any issues with me placing trpc route handler in the root of my api folder? I don't really Turborepo, nextjs, vite react app, express serverI have following structure Apps: First Frontend - Nextjs app Second Frontend - Vite ReactApp BackenRouter/Middleware Chaining in V10Heyo, finally migrating from v9 to v10 after putting it off for a while. Is it just me, or is this mthrowing custom errors from mutationsany idea why trpc is ignoring the catch expression? it just throws its own error about unique consttrpc in a pnpm monorepoHi all 👋 I was wondering if there is a recommended setup for monorepos, in our case with pnpm workTS Error with React when creating client "useContext" collides ....when creating the client i get following error: The property 'useContext' in your router collides wType 'NextRequest' is missing properties from type 'NextApiRequest'Enviorment: Node 18, pnpm Hi, I'm facing an error, where in my app i get this error at `createTRPCCType '{}' is not assignable in server queryType '{ input: { slug: string; }; "": any; }' is not assignable to type 'string | StringFilter<"CateThe inferred type of this node exceeds the maximum length the compiler will serialize.Using HTTP:POST for `query`?Hey guys, thanks for the awesome library! My application involves making a `query` with a large amre validation on static site next js 13Hi, does any one know how to make revaluation when I’m fetching data on the server client from DB wiTransformers not transforming data (trpc-sveltekit)I'm having some trouble getting superjson to do its magic with tRPC & SvelteKit. I have a `client.tsIssue Inferring Type on Frontend with ElectroDB Query Return StatementHi all, I am using ElectroDB to work with DynamoDB, and I have a Lambda function that uses tRPC thaWrong JSON response when deployedWhen testing in localhost in dev mode there is no issue and the response is correct as expected. BuExternal callsHi! I am using T3 stack, tRPC together with clerk, and i need to create users within the app, being Need help identifying the generic client side type of proceduresHi! I think my question is better explained by what I'm trying to achive than anything else: I likIs there a way to use versioning for procedures?I want to make multiple versions (v1 / v2) for a procedure, can i do it in procedure level?createSSGHelpersI'm trying to fetch data in getStaticProps and getting the issue "Promise<{ paths: { params: { id: nTRPC undefined when exportingHi i am working on merging routers from different files but when exporting the router property it coTRPC retries with new app dir```ts let { data: name, isLoading, isFetching, isError, error } = trpc.home.home.useQuery(); ```