T
tRPC

Looking to fix my tRPC implementation

Looking to fix my tRPC implementation

NNehilor4/25/2023
Hi guys I am looking for some help implementing tRPC in my current project, I have 3 files that need to be reviewed I think I almost have it but for some reason I am getting some errors. My goal is to replace the restful API endpoints and instead use tRPC. My first file is: src/server/app.ts Content:
import {
addContextHandler,
finalize,
initialize,
logger,
} from '@core-ui/service';
import * as dotenv from 'dotenv';
import express from 'express';
import { resolve } from 'path';
import 'reflect-metadata';
import { tRPCConfig } from './tRPC';

/* Refresh the token every 5 minutes */
dotenv.config();
export const app = express();

initialize({
app,
});

addContextHandler(app);

app.use('/lib', express.static(resolve('dist/lib'), {}));

app.use('/trpc', tRPCConfig);
logger.info('Current env = ${process.env.NODE_ENV}');
finalize({ app });
import {
addContextHandler,
finalize,
initialize,
logger,
} from '@core-ui/service';
import * as dotenv from 'dotenv';
import express from 'express';
import { resolve } from 'path';
import 'reflect-metadata';
import { tRPCConfig } from './tRPC';

/* Refresh the token every 5 minutes */
dotenv.config();
export const app = express();

initialize({
app,
});

addContextHandler(app);

app.use('/lib', express.static(resolve('dist/lib'), {}));

app.use('/trpc', tRPCConfig);
logger.info('Current env = ${process.env.NODE_ENV}');
finalize({ app });
NNehilor4/25/2023
Second file: src/server/tRPC/index.ts Content:
import { inferAsyncReturnType, initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import config from 'config';
import { z } from 'zod';

const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => {
return {
req,
res,
};
};

type Context = inferAsyncReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();

const { router } = t;
const publicProcedure = t.procedure;

const alertsRouter = router({
featureHealthAlerts: publicProcedure
.input(
z.object({
serviceAlias: z.string().nullish(),
}),
)
.query(async ({ input }) => {
try {
const serviceAlias = input.serviceAlias ?? 'kong';
const baseURL: unknown = config.get(
`coreUI.service.serviceProxies.${serviceAlias}.baseURL`,
);
const response: any = await fetch(`${baseURL}`);
return response;
} catch (error: any) {
throw new Error(error?.message);
}
}),
});

const appRouter = router({
alerts: alertsRouter,
});

export type AppRouter = typeof appRouter;

const tRPCConfig = trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
onError({ error }) {
console.error('Something went wrong', error);
},
batching: {
enabled: true,
},
});

export { tRPCConfig };
import { inferAsyncReturnType, initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import config from 'config';
import { z } from 'zod';

const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => {
return {
req,
res,
};
};

type Context = inferAsyncReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();

const { router } = t;
const publicProcedure = t.procedure;

const alertsRouter = router({
featureHealthAlerts: publicProcedure
.input(
z.object({
serviceAlias: z.string().nullish(),
}),
)
.query(async ({ input }) => {
try {
const serviceAlias = input.serviceAlias ?? 'kong';
const baseURL: unknown = config.get(
`coreUI.service.serviceProxies.${serviceAlias}.baseURL`,
);
const response: any = await fetch(`${baseURL}`);
return response;
} catch (error: any) {
throw new Error(error?.message);
}
}),
});

const appRouter = router({
alerts: alertsRouter,
});

export type AppRouter = typeof appRouter;

const tRPCConfig = trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
onError({ error }) {
console.error('Something went wrong', error);
},
batching: {
enabled: true,
},
});

export { tRPCConfig };
Third file: src/client/tRPC/index.ts Content:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `/`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `/`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
Whats my goal? I would like to get results using this query for example:
import { client } from '../../tRPC';
const test = client.alerts.featureHealthAlerts.query({ serviceAlias: 'kong' });
test.then(data => {
console.log('data => ', data);
});
import { client } from '../../tRPC';
const test = client.alerts.featureHealthAlerts.query({ serviceAlias: 'kong' });
test.then(data => {
console.log('data => ', data);
});
This is my result:
Nnlucas4/25/2023
You’ve added a prefix on the server but the errors don’t show the prefix So you need the prefix on your client
NNehilor4/25/2023
Should be the same prefix @Nick Lucas ? or something different? Sorry I am new on this
Nnlucas4/25/2023
It's just a HTTP URI You wouldn't take out a rental agreement at 231 Spooner Street and then be surprised when all your stuff isn't in 234 Spooner Street. It's a different location If you host tRPC at one URL, don't be surprised when a different URL returns a 404
NNehilor4/25/2023
Ok I have added this: src/client/tRPC/index.ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `http://localhost:2021/trpc`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `http://localhost:2021/trpc`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
Result:
Nnlucas4/25/2023
What's the actual error code now? And is the port you've set actually correct? I don't see that in your API setup
NNehilor4/25/2023
I am getting this:
NNehilor4/25/2023
My app uses 3000
Nnlucas4/25/2023
What port is the API on though? the updated code is port 2021, the error says 4000. Something's wrong 😄
NNehilor4/25/2023
Yeah I updated it one sec My app works on this port: https://localhost.sparkcognition.com:3000/ I mean reactjs, so should I use this config:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = 'https://localhost.sparkcognition.com:3000';

const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = 'https://localhost.sparkcognition.com:3000';

const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
This is where I am not sure
NNehilor4/25/2023
NNehilor4/26/2023
Hi @nlucas sorry for bothering you, please let me know when you have a few mins to help me with this, thanks
Nnlucas4/26/2023
This strikes me as needing to go back to basics a little. Setting a URL on both sides isn’t that hard, but throwing tRPC and next into the mix isn’t helping you Why not follow an Express tutorial and just try to get a simple rest endpoint going and a simple react spa connect to it? Then you can start swapping out parts and add tRPC to the express API
NNehilor4/27/2023
I am following this guide but I am still getting the error: https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/express-server @Nick Lucas I managed to fix it, thanks so much for the help! it was related with the address: Server
app.use('/trpc', tRPCConfig);
app.use('/trpc', tRPCConfig);
Client
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: '/trpc',
}),
],
});
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: '/trpc',
}),
],
});

Looking for more? Join the community!

T
tRPC

Looking to fix my tRPC implementation

Join Server
Recommended Posts
Expression produces a union type that is too complex to representHi! I have started to encounter the above on error on pretty simple react components using trpc v10 Skipping useQuery with typescriptI'm wondering if there is a way to skip a query in a typescript friendly way? `rtk-query` has a handClerk Webhook Input UndefinedHi! I wrote a public procedure that takes in an input and updates user info based on Clerk Webhook. Getting this error: Cannot read properties of undefined (reading 'upsert')I'm using the T3 Stack. And I'm fairly new to tRPC so I am not sure what this error is caused. I'm Stuck trying to utilize useQuery to fetch some data on form submissionI'm trying to call a procedure in trpc through the use of useQuery in react upon form submission. SocreateTRPCNext type errorHi everyone. So I started creating nextjs app with trpc + prisma set up. and when i use my AppRouterFull cache invalidation and timing problemI'm really enjoying using the full cache invalidation https://trpc.io/docs/reactjs/usecontext#invaliUsing Next.JS + FastifyMy node environment is Node 18, powered by PNPM. What's wrong: I have a few requirements for my appError Handling vs Error FormattingI'm a bit confused from the docs about how I should be handling errors on the server. The Error HandNext.js body-parsing issueA thead to discuss this issue: https://github.com/trpc/trpc/issues/4243Cannot find module '@trpc/react-query/server' or its corresponding type declarations```ts import { createServerSideHelpers } from '@trpc/react-query/server' ``` This should work, righProcedure with generic input?Is there a way to define a procedure so that it takes input with type parameters, and returns outputDelete item {0: {json:{id: 12324}}}When i try to mutate/delete item with id i am geting this payload `{0: {json:{id: 12324}}}`, withouQuery function depends on a variableIn tRPC v10 accessing a specific path is really easy, but because of that I don't control the query 'useInfiniteQuery' hook disappeared after moving to TurborepoI am using Turborepo with Next.js with the following layout, originally a T3 app - `/apps/app` - `/pconvert the result to date objectsI am not sure if this is even trpcs responsibility but I would like to get my date objects as date oECONNREFUSED with TRPC call on VercelAnyone run into this before? I just deployed my app to Vercel and I run into this error when I triggInvalid ValDoes TRPC string input have a limit? https://prnt.sc/KlXlyoGrzP8P Edit: It was actually from stripis possible to combine next-minimal-starter with react-router-dom ?Hi, I'm trying to combine https://github.com/trpc/trpc/tree/main/examples/next-minimal-starter and rusing same query for entries appHow to use same query for many components? I don't want to request api for many times ;-; I can't p