<DxD/><
tRPC3y ago
16 replies
<DxD/>

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,
    });
  };
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 });
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,
    },
  });
});
Was this page helpful?