T
tRPC

❓-help

ReferenceError: Cannot access 'appRouter' before initialization

KKay12/23/2023
Hi friends im having trouble implementing a "protected" or "private" procedure in TRPC using Next.js 14 with NextAuth.
import { TRPCError, initTRPC } from "@trpc/server";
import superjson from "superjson";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { getServerAuthSession } from "./auth";
import { Session } from "next-auth";

type CreateContextOptions = {
session: Session | null;
};

const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
//prisma,
};
};

export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;

const session = await getServerAuthSession({ req, res });

return createInnerTRPCContext({
session,
});
};

const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,
});

const isAuthed = t.middleware(({ ctx, next }: any) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
session: { ...ctx.session, user: ctx.session.user },
},
});
});

export const router = t.router;
export const protectedProcedure = t.procedure.use(isAuthed);
export const publicProcedure = t.procedure;
import { TRPCError, initTRPC } from "@trpc/server";
import superjson from "superjson";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { getServerAuthSession } from "./auth";
import { Session } from "next-auth";

type CreateContextOptions = {
session: Session | null;
};

const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
//prisma,
};
};

export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;

const session = await getServerAuthSession({ req, res });

return createInnerTRPCContext({
session,
});
};

const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,
});

const isAuthed = t.middleware(({ ctx, next }: any) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
session: { ...ctx.session, user: ctx.session.user },
},
});
});

export const router = t.router;
export const protectedProcedure = t.procedure.use(isAuthed);
export const publicProcedure = t.procedure;
If i understand this correctly it should be setting a context for trpc. The context is the session object from the nextauth function getServerSession
import { httpBatchLink } from "@trpc/client";

import { appRouter } from "@/server";
import { ServerConfig } from "@/config/server";

export const TrpcClientServer = appRouter.createCaller({
links: [
httpBatchLink({
url: `${ServerConfig.NEXTAUTH_URL}/api/trpc`,
}),
],
});
import { httpBatchLink } from "@trpc/client";

import { appRouter } from "@/server";
import { ServerConfig } from "@/config/server";

export const TrpcClientServer = appRouter.createCaller({
links: [
httpBatchLink({
url: `${ServerConfig.NEXTAUTH_URL}/api/trpc`,
}),
],
});
Nnlucas12/23/2023
This likely means you have a circular import Also not sure what you're doing in that last file, but that's definitely not how you use createCaller, I think you need to revisit the docs

Looking for more? Join the community!

Recommended Posts
trpc openapi does not work on app routerhttps://github.com/jlalmes/trpc-openapi Can i just know if trpc open api for next is also applicableSubscription types are not inferred while queries and mutations are working fineI am NOT working with a monorepo but while query and mutation types are being inferred out of the boHow are thrown (unhandled) exceptions safe to pass?Hi, I started looking into error handling more and understand that all errors get wrapped in a TRPCECanary useUtils and createTRPCQueryUtils type not callableTrying to access utils object in my application after using `useUtils` or `createTRPCQueryUtils` andtRPC run express under the hood?tRPC run `expressjs` under the hood?Modify mutation error messages?We occasionally get timeouts from cloudfront which gives the user an error about how the cloudfront server-side helpers doesnt work with `Hydrate` and `QueryClient`environtment: node v20.9.0, npm Hi i tried to implement server-side helpers but somehow it just doesUnable to mock unstable_batchStreamLink network responseHi there! I have a couple API endpoints that call third party dependencies and would like to mock a Using trpc with fastify server and nextjs clientHello, is it possible to use fastify for server and have a nextjs client and make use of the SSG / SI can't mutate or query in SvelteKitEnvironment: Node 20 with Yarn I'm not getting any specific errors but I don't get the "mutate" or "TRPCError class, public readonly cause?: Error; this line should have override functionhey i am trying to use the TRPCError for throwing errors in my apps, but i am getting this error, chWhy do people use SplitLink? (http + websocket)Why not just use websockets for everything? Just curious.