As stated in the tRPC
s official documentation, the query parameters must adhere to this specific format:
myQuery?input=${encodeURIComponent(JSON.stringify(input))}
Here is an example of a procedure:
hello: publicProcedure
.input(z.object({ text: z.string() }))
.output(z.object({ greeting: z.string() }))
.query(({ input }) => {
return {
greeting: `Hello ${input.text}`,
};
}),
An attempt to manually create a URL results in an error:
const data = {text: "my message"}
const res = await fetch('http://localhost:3000/api/trpc/example.hello?batch=1&input='+encodeURIComponent(JSON.stringify(data)), { method: 'GET' });
const body = await res.json();
console.log(body);
The error suggests that there might be an issue with the encoding of the query parameters. Any insights on what could be going wrong here? Interestingly, it works using the client:
const test = api.example.hello.useQuery({ text: "my message" });
{
"error": {
"json": {
"message": "[\n {\n \"code\": \"invalid_type\",\n \"expected\": \"object\",\n \"received\": \"undefined\",\n \"path\": [],\n \"message\": \"Required\"\n }\n]",
"code": -32600,
"data": {
"code": "BAD_REQUEST",
"httpStatus": 400,
"stack": "...TRPCError and more details..."
"path": "example.hello"
}
}
}
}
I examined the query sent by the client (
const test = api.example.hello.useQuery({ text: "my message" });
) through my browser, which resulted in success.
http://localhost:3000/api/trpc/example.hello?batch=1&input=%7B%220%22%3A%7B%22json%22%3A%7B%22text%22%3A%22my%20message%22%7D%7D%7D
If I decode the input query parameter, I get
{"0":{"json":{"text":"my message"}}}
Even when I structure my data object in the same manner and encode it accordingly, the query still fails:
const data = {"0":{"json":{"text":"my message"}}}
const res = await fetch('http://localhost:3000/api/trpc/example.hello?batch=1&input='+encodeURIComponent(JSON.stringify(data)), { method: 'GET' });
const body = await res.json();
console.log(body);
The presence of the 0
seems to be necessary due to batching being enabled. However, the inclusion of the json
field seems peculiar.
{"0":{"json":{"text":"my message"}}}
Any thoughts on why my constructed fetch request is failing? What would be the correct format for encoding or structuring the object?