T
tRPC

Difference between createTRPCNextAppDirServer, createTRPCNext and createTRPCProxyClient?

Difference between createTRPCNextAppDirServer, createTRPCNext and createTRPCProxyClient?

IIgnition 9811/12/2023
Hey everyone. I struggle to understand the difference between these 3 TRPC functions when it come to using it in server.ts to be able to make server side API calls. I'm using NextJS 14 and app router. Is there clear differentiation between these 3? This project is for a production release. Would greatly appreciate a little break down. Thanks!
DDxD11/12/2023
I belive you are talking about initTRPC, initTRPCBrowser, and initTRPCServer, right ?
IIgnition 9811/12/2023
I'm referring to step 3 from the docs. https://trpc.io/docs/server/data-transformers Currently I'm using the following structure to make server side calls to my database:
export const api = createTRPCProxyClient<AppRouter>({
transformer: superjson, // <--
// [...]
});
export const api = createTRPCProxyClient<AppRouter>({
transformer: superjson, // <--
// [...]
});
export default async function Home() {
const hello = await api.post.hello.query({ text: "from tRPC" });
return (
<p className="text-2xl text-white">
{hello ? hello.greeting : "Loading tRPC query..."}
</p>
)
}
export default async function Home() {
const hello = await api.post.hello.query({ text: "from tRPC" });
return (
<p className="text-2xl text-white">
{hello ? hello.greeting : "Loading tRPC query..."}
</p>
)
}
I don't quite get what benefit I'd get if I was to use createTRPCNextAppDirServer or createTRPCNext instead of createTRPCProxyClient as all of them are capable of making server side calls.
DDxD11/12/2023
The difference between createTRPCProxyClient, createTRPCNext, and createTRPCNextAppDirServer lies in their use cases and intended usage scenarios. createTRPCProxyClient: Use Case: This is intended for client-side usage. It allows you to create a client proxy that can be used on the client to make tRPC queries. It's suitable for scenarios where you need to make requests from the client to the server. createTRPCNext: Use Case: This is designed for server-side usage within Next.js API routes. It provides an instance of TRPCClient specifically configured for server-side rendering (SSR) within Next.js. createTRPCNextAppDirServer: Use Case: This is a variant of createTRPCNext but is specifically intended for server rendering within Next.js when your api directory is within your app directory. In summary Use createTRPCProxyClient for client-side usage. Use createTRPCNext for server-side rendering within Next.js API routes. Use createTRPCNextAppDirServer if your API directory is within your app directory and you want server-side rendering in that specific setup. I hope it helps Also, have u ever create a full auth system with trpc next and jwt ?
IIgnition 9811/12/2023
Thanks a lot for the detailed answer! No, I haven't. That's what I'm trying to do atm with Next, TRPC and Supabase Auth.
DDxD11/12/2023
Any time Ohh…I am trying for days And nothing
IIgnition 9811/12/2023
Also Supabase setup?
DDxD11/12/2023
No, I use mongodb
IIgnition 9811/12/2023
What are you having problems with?
DDxD11/12/2023
After I log in, I can not send my custom headers to my context With that context I check if user has a token And then he can access protected procedures If u solve auth…can u share the git ?
IIgnition 9811/12/2023
Sure
DDxD11/12/2023
@Ignition 98
import { TRPCError } from '@trpc/server';
import { db } from 'db';
import jwt from 'jsonwebtoken';
import { checkSamePassword } from 'utils/hash/checkSamePassword';
import keys from 'utils/secret/keys';
import { z } from 'zod';

import { router, publicProcedure } from '..';

export const loginRouter = router({
login: publicProcedure
.input(
z.object({
email: z.string().nonempty('Email is required').email('Invalid email address'),
password: z.string().nonempty('Password is required').min(6),
}),
)
.query(async ({ ctx, input: { email, password } }) => {
const user = await db.user.findOne({ email: email });

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const validatePassword = await checkSamePassword(password, user?.password);
if (!user || !validatePassword) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Email or password is not valid, please try again.',
});
} else {
const token = jwt.sign({ _id: user._id }, keys.jwtSecret, { expiresIn: '1h' });
const refreshToken = jwt.sign({ _id: user._id }, keys.jwtSecret, { expiresIn: '1h' });

ctx.res.cookie('access_token', refreshToken, {
httpOnly: true,
secure: true,
});

return {
// headers: {
// authorization: `Bearer ${token}`,
// },
data: {
token,
},
};
}
}),
});
import { TRPCError } from '@trpc/server';
import { db } from 'db';
import jwt from 'jsonwebtoken';
import { checkSamePassword } from 'utils/hash/checkSamePassword';
import keys from 'utils/secret/keys';
import { z } from 'zod';

import { router, publicProcedure } from '..';

export const loginRouter = router({
login: publicProcedure
.input(
z.object({
email: z.string().nonempty('Email is required').email('Invalid email address'),
password: z.string().nonempty('Password is required').min(6),
}),
)
.query(async ({ ctx, input: { email, password } }) => {
const user = await db.user.findOne({ email: email });

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const validatePassword = await checkSamePassword(password, user?.password);
if (!user || !validatePassword) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Email or password is not valid, please try again.',
});
} else {
const token = jwt.sign({ _id: user._id }, keys.jwtSecret, { expiresIn: '1h' });
const refreshToken = jwt.sign({ _id: user._id }, keys.jwtSecret, { expiresIn: '1h' });

ctx.res.cookie('access_token', refreshToken, {
httpOnly: true,
secure: true,
});

return {
// headers: {
// authorization: `Bearer ${token}`,
// },
data: {
token,
},
};
}
}),
});
any idea why is not store in cookie ?
DDxD11/12/2023
No description
IIgnition 9811/12/2023
No idea tbh..

Looking for more? Join the community!

T
tRPC

Difference between createTRPCNextAppDirServer, createTRPCNext and createTRPCProxyClient?

Join Server
Recommended Posts
What is the mutation error type?In the provider I want to set onError for all mutations: ```ts new QueryClient({ defauMerging two clients into oneI have two clients. One for react-query for client components and one for server components. I wannaIs it possible to only use WebSockets when necessary, otherwise use httpbatch or http?I have an application, and on certain pages I need live data. Is there a way to only have tRPC open Zod transform typesI have a zod type for our backend requirements that looks like this: ```javascript const ZCustomTypeuseQuery in App Router?I have a client component that I want to use useQuery in like in pages router, but only `query` is aTranform output data using middleware after handler has run - possible?As the title says, been trying for a couple of hours to modify the return type of the data using midCan we configure cache on a per-request basis?Hi! I’m a big fan of tRPC! I’ve been using it for quite some time. I actually have 2 questions: ## Error in tRPC with Clerk in t3-app routerHi guys, im trying to implement clerk auth in t3 app router. But it gives me this error when im tryiError when converting string from router.query to prisma DB enumHey yall, I'm working on a Next.js application using tRPC and Prisma, and I've encountered an invaliNext.js tRPC router separated to edge-runtime and node-runtimeI would like to separate server into two runtimes - most things can run on edge-runtime, but I have [How To?] Create a record in database on form submission...I have an application using trpc, Cloudfare D1 database, and trpc. I am trying to use a tamagui forHow to obfuscate data via transformerEnd user with adequate knowledge can easily copy JSON data in plain text from network requests in brResponse delay from TRPC using postgresqlI'm using TRPC as backend and for the database using postgresql so while creating using facing delayCapture TRPCClientError so that it does not show in the client's browser consoleIf a TRPCError is thrown from a router procedure, the client will receive a TRPCClientError that wilNetlify function EMFILEIf this is a dumb question just point me in the direction of the stackoverflow. I've scoured discorempty `input` object when using mutationWhen using `useQuery` I have no issues even with input but when using `useMutation`. The backend is Returning html with TRPCIs it possible to return content-types other than JSON, so HTML for example? I have a requirement thSpecify invalid queries from the server?I have a TRPC app that I am writing and there are times I would like to invalidate queries on the clAutomatically notify about excess queried fields.Hello! Imagine very common situation: We picking "user" with 10 fields, but using only 3 of them in The inferred type of 'trpc' cannot be named without a reference ...Hey everyone, I just changed around the structure of my monorepo where I now have my nextjs applica