trpc cors

my sveltekit app is running on https://example.com with tRPC and it's making requests to http://127.0.01:3001/api/trpc (otherwise it won't work) but I'm getting a CORS error (' The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3001/api/trpc/model.getAll?batch=1&input=%7B%7D. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)'). how can I fix this?
N
Nick331d ago
What Adapter are you using on the backend? You just need to enabled CORS and whitelist the frontend
N
Nick331d ago
Standalone Adapter | tRPC
tRPC's Standalone Adapter is the simplest way to stand up your application. It's ideal for local development, and for server-based production environments. In essence it's just a wrapper around the standard Node.js HTTP Server with the normal options related to tRPC.
O
oscarama331d ago
I'm not using any adapter
// public.ts
import type { ContextType } from "./context";
import { initTRPC } from "@trpc/server";

const t = initTRPC.context<ContextType>().create();

export const middleware = t.middleware;
export const router = t.router;
// public.ts
import type { ContextType } from "./context";
import { initTRPC } from "@trpc/server";

const t = initTRPC.context<ContextType>().create();

export const middleware = t.middleware;
export const router = t.router;
it's all in one repo with sveltekit and sveltekit is using adapter-node might it be a sveltekit issue?
N
Nick331d ago
You're always using an Adapter, you might just not have recognised it Whatever you're using to host tRPC inside Svelte is the adapter, and something in that or Svelte will need CORS setting up Might be worth having a look at the docs you've been following, and any github issues for the project
O
oscarama331d ago
const handleTRPC: Handle = async ({ event, resolve }) => {
if (event.request.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
},
});
};

if (event.url.pathname.startsWith(`${trpcPathBase}/`)) {
const response = await fetchRequestHandler({
endpoint: trpcPathBase,
req: event.request,
router: appRouter,
createContext: () => {
return createContext(event);
},
});

response.headers.append("Access-Control-Allow-Origin", "*");

return response;
};

// eslint-disable-next-line no-return-await
return await resolve(event);
};
const handleTRPC: Handle = async ({ event, resolve }) => {
if (event.request.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
},
});
};

if (event.url.pathname.startsWith(`${trpcPathBase}/`)) {
const response = await fetchRequestHandler({
endpoint: trpcPathBase,
req: event.request,
router: appRouter,
createContext: () => {
return createContext(event);
},
});

response.headers.append("Access-Control-Allow-Origin", "*");

return response;
};

// eslint-disable-next-line no-return-await
return await resolve(event);
};
with svelte I have this
N
Nick331d ago
👍 looks about right
O
oscarama331d ago
mind you it does work locally, but when I put it on the VPS I get the cors error
N
Nick331d ago
Got it, yes that looks fine locally, but the infrastructure itself is almost always its own setup
O
oscarama331d ago
and if I dont use 127.0.0.1 I get a 500 Fetch Failed error with no extra message and I'm using nginx idk if any of that has any bearing
N
Nick331d ago
You'll need to figure out where the request is terminating, if nginx is saying no then config that, if it's reaching tRPC then something else might be wrong Check logs etc, deploying to custom infra is always a bit of a debugging process 😄
O
oscarama331d ago
TRPCClientError: fetch failed yeah, I'm using pm2 in this case is all I get in the logs
N
Nick331d ago
That log is from the client though, not the bakend nginx will have logs, pm2 will have some logs, but there may be other things with logs depending on your server setup
O
oscarama331d ago
got it
N
Nick331d ago
O
oscarama331d ago
perhaps. I'll try that, thanks
O
oscarama331d ago
no change
O
oscarama330d ago
issue is fixed by the way, some obscure issue with nginx (or I'm just ignorant lol). thanks for your help
More Posts
T3 app tRPC external callsCurrently i'm just making Post request and formatting my payload to ```{ "0": { "json":Next-auth session not being fetched in tRPC contextNext-auth session not being fetched in tRPC contextuseMutation not handeling arguments correctly.Hello, I have a mutation setup on the server with the input being an object containing the fields emUpdate Clerk Organization from TRPC Router (T3 Stack)Hello, if anyone got an idea on how to handle this I would highly appreciate it. I have some organiHow to not send request in specific condition in useQuery()```js const { data: artists, isLoading } = api.findArtist.useQuery({ name: search, }); ``` TRPCClientError: fetch failedI get the below error when createTRPCProxyClient runs on BE of a Next.JS app hosted on Vercel: ```TinferRouterOutputs not inferringCould anyone point me in the right direction to why my types aren't being inferred here? (Using T3 bModular Router ThoughtsHello, I hope I can convey clearly what I hope to accomplish. To start, I have a monorepo, with a feIssue with trpc fetch when trying to pass Clerk auth to contextI'm currently trying to add Clerk auth to my trpc context, but I just keep getting this error: `ErrBullMQ + TRPCCurious how to configure BullMQ with TRPC correctly. Currently I have the queue, queueevents, and thTrpc refetches all of the queries when i run a mutationIm running node 16.15.0 with Pnpm When i run a mutation for some reason all of the queries get refettRPC Client on NodeJS server keeps complaining that no fetcher has been configuredHey, I want to create a tRPC setup where I have one server (works fine) and then a client which is cBest Practice to Fetch a Query OnDemandWhat's the best practice to fetch a query on demand? I don't have the context for the query's inputOutput Response ShapeI'm wondering, is the output response shape locked in, or can we modify it in any way? For example: Need help```js import {initTRPC} from '@trpc/server'; import * as trpcNext from '@trpc/server/adapters/next';useQuery hook modify data on fetch.Hello is it possible to modify the data that is fetched with useQuery hook in tRPC basically im storAccepting a DecoratedProcedure with inputs and outputs that extend some given typesIs there any way to accept a DecoratedProcedure that extends { mutate: Resolver<TProcedure> } where useEffect and useMutation error about conditional rendering of hooksI am using t3 stack with tRPC, and I am trying to mark all emails as seen when the page loads by usiGuide to create an adapterIs there a guide on the docs that explains the basics to create an adapter?Does tRPC websocket client supports wss protocol?After changing the websocket client url from ws to wss, it fails to connect. Tested out the connecti