rhh4x0R
rhh4x0R3w ago

Getting CORS error with tRPC express adapter, locally

I've got a Vite + tRPC backend (same repo) that I'm struggling to get queries from. I'm just getting 'Failed to Fetch' on the UI and Network says it's a Cors error. Here's my trpcClient
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:4000/trpc',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
}),
],
}),
);
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:4000/trpc',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
}),
],
}),
);
and my Express setup on the server
import express from 'express';
import env from '@server/utils/env';
import { createExpressMiddleware } from '@trpc/server/adapters/express';
import { appRouter } from '@server/trpc/router';
import { createContext } from '@server/trpc/context';
//import { initDb } from '@server/db';
import ViteExpress from 'vite-express';

const app = express();

app.use(
'/trpc',
createExpressMiddleware({
router: appRouter,
createContext,
onError({ error, type, path, input, ctx, req }) {
console.error(`Error in ${type} ${path}:`, error);
},
})
);

//env.PORT
ViteExpress.listen(app, 4000, () => {
console.log(`Server is running on port ${env.PORT}`);
});
import express from 'express';
import env from '@server/utils/env';
import { createExpressMiddleware } from '@trpc/server/adapters/express';
import { appRouter } from '@server/trpc/router';
import { createContext } from '@server/trpc/context';
//import { initDb } from '@server/db';
import ViteExpress from 'vite-express';

const app = express();

app.use(
'/trpc',
createExpressMiddleware({
router: appRouter,
createContext,
onError({ error, type, path, input, ctx, req }) {
console.error(`Error in ${type} ${path}:`, error);
},
})
);

//env.PORT
ViteExpress.listen(app, 4000, () => {
console.log(`Server is running on port ${env.PORT}`);
});
I've also just tried
app.use(4000)
app.use(4000)
-- I had ViteExpress up and running a year ago and that worked fine though. I'm running this locally so I don't understand why CORS would be an issue. As you can see I've added the CORS info as seen here: https://trpc.io/docs/client/cors Any ideas?
Send cookies cross-origin | tRPC
If your API resides on a different origin than your front-end and you wish to send cookies to it, you will need to enable CORS on your server and send cookies with your requests by providing the option {credentials: "include"} to fetch.
No description
Solution:
I realized that I could just run the tRPC server and that also runs the client somehow — so no need for different ports and causing cors issues.
Jump to solution
1 Reply
Solution
rhh4x0R
rhh4x0R2w ago
I realized that I could just run the tRPC server and that also runs the client somehow — so no need for different ports and causing cors issues.