Need help how to send headers in trpc

project is setup with express on 2 parts,cleint and server i have this pice of cod in client side
const { mutate: mutateCreateUser } = trpcApi.register.register.useMutation({
onError: (error) => {
const errorMessage = error.data?.httpStatus === 409 ? error.message : 'Passowrd must contains 6 characters';
if (errorMessage) {
setShowError(errorMessage);
setIsError(true);
setTimeout(() => {
setShowError('');
setIsError(false);
}, 5000);
}
},
// onSuccess:()=>{}
});

const createUser = (): void => {
mutateCreateUser({
...logInUser,
});
};
const { mutate: mutateCreateUser } = trpcApi.register.register.useMutation({
onError: (error) => {
const errorMessage = error.data?.httpStatus === 409 ? error.message : 'Passowrd must contains 6 characters';
if (errorMessage) {
setShowError(errorMessage);
setIsError(true);
setTimeout(() => {
setShowError('');
setIsError(false);
}, 5000);
}
},
// onSuccess:()=>{}
});

const createUser = (): void => {
mutateCreateUser({
...logInUser,
});
};
here i send a small obj(email,password,confirm password) to create an user ,, this is my context
import { inferAsyncReturnType } from '@trpc/server';
import { initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import superjson from 'superjson';

export function createContext(opts: trpcExpress.CreateExpressContextOptions) {
let token: string | null = null;
if (opts.req.headers.authorization) {
token = opts.req.headers.authorization.split(' ')[1];
}
return { req: opts.req, res: opts.res, token };
}

export type Context = inferAsyncReturnType<typeof createContext>;

export const t = initTRPC.context<Context>().create({ transformer: superjson });
import { inferAsyncReturnType } from '@trpc/server';
import { initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import superjson from 'superjson';

export function createContext(opts: trpcExpress.CreateExpressContextOptions) {
let token: string | null = null;
if (opts.req.headers.authorization) {
token = opts.req.headers.authorization.split(' ')[1];
}
return { req: opts.req, res: opts.res, token };
}

export type Context = inferAsyncReturnType<typeof createContext>;

export const t = initTRPC.context<Context>().create({ transformer: superjson });
and my middleware
import { TRPCError } from '@trpc/server';
import { decodeAndVerifyJwtToken } from 'utils/check/jwtToken';

import { t } from '../context';

export const authMiddleware = t.middleware((opts) => {
const { ctx } = opts;
if (!ctx.token) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'aici se opreste' });
}
const user = decodeAndVerifyJwtToken(ctx.token);
return opts.next({
ctx: {
req: ctx.req,
res: ctx.res,
user,
},
});
});
import { TRPCError } from '@trpc/server';
import { decodeAndVerifyJwtToken } from 'utils/check/jwtToken';

import { t } from '../context';

export const authMiddleware = t.middleware((opts) => {
const { ctx } = opts;
if (!ctx.token) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'aici se opreste' });
}
const user = decodeAndVerifyJwtToken(ctx.token);
return opts.next({
ctx: {
req: ctx.req,
res: ctx.res,
user,
},
});
});
DxD
DxD187d ago
here is my index
import { t } from './context';
import { authMiddleware } from './middleware/auth';

export const router = t.router;
export const publicProcedure = t.procedure;

export const protectedProcedure = t.procedure.use(authMiddleware);
import { t } from './context';
import { authMiddleware } from './middleware/auth';

export const router = t.router;
export const publicProcedure = t.procedure;

export const protectedProcedure = t.procedure.use(authMiddleware);
When i use a route that has protectedProcedure how can i send with
headers.authorization
headers.authorization
?Like on client when i do a mutation/query i need to send smt or what ? every idea is wellcome
Nick
Nick186d ago
Have you read the docs? https://trpc.io/docs/client/headers
Custom header | tRPC
The headers option can be customized in the config when using the httpBatchLink or the httpLink.
DxD
DxD186d ago
Yes sir @Nick Lucas I really don’t understand Any chance you have something else ?
Nick
Nick186d ago
Not sure how we can provide anything simpler than that example showing setting the auth header in a Link? You could copy and paste the whole thing and it would probably work for you
DxD
DxD186d ago
Even is setup for express ? Cuz in doc if for next And I use express For next I understand how to use it But not for express @Nick Lucas
Nick
Nick186d ago
It shouldn’t matter, that’s client setup and that’s the piece you’re missing. Express is the backend
DxD
DxD186d ago
Aha I am really confused 😕 i will check how to set up in client
More Posts
"fetch failed" when buildingHi, we are running into an issue where building our production next app causes "fetch failed" errorsanyone has an example of SSR with React query working without Next js?Can't find a working exampleLooking for an up to date boilerplate for tRPC & Fastify.Looking for an up to date boilerplate for tRPC & Fastify.Can You Provide Guidance on Implementing RBAC and Share GitHub Examples?I am currently exploring the implementation of Role-Based Access Control (RBAC) and am seeking your `useQuery` not working?is it just me or does `useQuery` not work in my next js components? i try to call it and it says cliServer Component Call to TRPC on express backendI have following structure: - Nextjs App folder with both client components and server components - Can set cookie with trpc?I tried to create a full authentication system in trpc using jwt and refresh token I find that is notrying to understand how this worksso i'm looking at the t3 template that was made for me, and there seems to be a `trpc` folder that ccan't call nested routethis is the top level router: ```ts const appRouter = router({ hello: procedure.query(() => 'heltrpc authDid someone create a full auth system in trpc (with next js trpc react query prisma,jwt token, refreDifference between createTRPCNextAppDirServer, createTRPCNext and createTRPCProxyClient?Hey everyone. I struggle to understand the difference between these 3 TRPC functions when it come tWhat 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 invali