nicoalbanese / kirimase

Build full-stack Next.js apps, incredibly fast
https://kirimase.dev
MIT License
2.39k stars 107 forks source link

TRPCClientError after navigating to generated route #97

Closed keegn closed 7 months ago

keegn commented 7 months ago

After running kirimase generate and selecting the following (I've tried with API route as well) i'm consistently getting the error shown below when I navigate to a new generated route.

Screenshot 2023-11-30 at 10 31 51 PM Screenshot 2023-11-30 at 10 34 27 PM
nicoalbanese commented 7 months ago

Hey 👋 did you run your databases migrate command after running the generate command?

vaun-blu commented 7 months ago

I did. Also get the same error. Seems to be an issue when using the server side trpc caller? Exported as api in lib/trpc/api.ts.

Was getting the error below from clerk. Middleware wasn't properly bypassing trpc.

1. To prevent Clerk authentication from protecting (401) the api route, remove the rule matching "/api/trpc/users.getUsers" from the `apiRoutes` array passed to authMiddleware
2. To make the route accessible to both signed in and signed out users, pass `publicRoutes: ["/api/trpc/users.getUsers"]` to authMiddleware
3. To prevent Clerk authentication from running at all, pass `ignoredRoutes: ["/((?!api|trpc))(_next.*|.+\.[\w]+$)", "/api/trpc/users.getUsers"]` to authMiddleware
4. Pass a custom `afterAuth` to authMiddleware, and replace Clerk's default behavior of redirecting unless a route is included in publicRoutes

Switching the middleware config matcher from:

matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']

to

matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/((?!api|trpc))"]

seemed to solve the error.

vaun-blu commented 7 months ago

Never mind. Was working for a second, but just stopped.

keegn commented 7 months ago

I ran npx prisma db push (I'm using Planetscale) after the generate command.

nicoalbanese commented 7 months ago

can you share your kirimase.config.json? and the version of the cli you are using?

vaun-blu commented 7 months ago

can you share your kirimase.config.json? and the version of the cli you are using?

{
  "hasSrc": true,
  "packages": [
    "drizzle",
    "shadcn-ui",
    "clerk",
    "trpc"
  ],
  "preferredPackageManager": "pnpm",
  "t3": false,
  "alias": "@",
  "rootPath": "src/",
  "orm": "drizzle",
  "componentLib": "shadcn-ui",
  "provider": "better-sqlite3",
  "driver": "sqlite",
  "auth": "clerk"
}

Here is my config and I am using v0.0.36. I get the error every time I try using the server side trpc client in a server route.

export default async function Account() {
  await checkAuth();
  const { session } = await getUserAuth();

  // Error using server side api
  const data = await api.users.getUsers.query();

  return (
    <main>
      <h1 className="text-3xl font-semibold my-6">Account</h1>
      <div className="space-y-6">
        <UserSettings session={session} />
      </div>
    </main>
  );
}
nicoalbanese commented 7 months ago

I figured it out! Turns out I made a very silly mistake. Earlier this week we did a complete rewrite of the trpc implementation to mimic T3 (as we were running into issues with protected procedures). To save previous work, I wrote these new generators in new functions and forgot to update the function invocation for the lib/trpc/api.ts so it was still generating the previous implementation. I'm patching it now with a few other updates and will update the package soon after (later this eve). Apologies again for the issues!

kirso commented 7 months ago

@nicoalbanese I've been banging my head about this since both happened to me for pay to tweet and linktree for the past 2 hours 😂. Since we've generated these routes already, do you mind also letting us know what the fix is without scaffolding the entire thing again?

nicoalbanese commented 7 months ago

of course and really sorry again for that! update your lib/trpc/api.ts file to be the following:

import "server-only";

import { appRouter } from "@/lib/server/routers/_app";
import { env } from "@/lib/env.mjs";
import { createTRPCContext } from "./context";

import {
  createTRPCProxyClient,
  loggerLink,
  TRPCClientError,
} from "@trpc/client";
import { callProcedure } from "@trpc/server";
import { type TRPCErrorResponse } from "@trpc/server/rpc";
import { observable } from "@trpc/server/observable";

import { cache } from "react";
import { cookies } from "next/headers";

import SuperJSON from "superjson";

const createContext = cache(() => {
  return createTRPCContext({
    headers: new Headers({
      cookie: cookies().toString(),
      "x-trpc-source": "rsc",
    }),
  });
});

export const api = createTRPCProxyClient<typeof appRouter>({
  transformer: SuperJSON,
  links: [
    loggerLink({
      enabled: (op) =>
        env.NODE_ENV === "development" ||
        (op.direction === "down" && op.result instanceof Error),
    }),
    /**
     * Custom RSC link that lets us invoke procedures without using http requests. Since Server
     * Components always run on the server, we can just call the procedure as a function.
     */
    () =>
      ({ op }) =>
        observable((observer) => {
          createContext()
            .then((ctx) => {
              return callProcedure({
                procedures: appRouter._def.procedures,
                path: op.path,
                rawInput: op.input,
                ctx,
                type: op.type,
              });
            })
            .then((data) => {
              observer.next({ result: { data } });
              observer.complete();
            })
            .catch((cause: TRPCErrorResponse) => {
              observer.error(TRPCClientError.from(cause));
            });
        }),
  ],
});
nicoalbanese commented 7 months ago

Updated and should be resolved with 0.0.37 😊

also added functions to automatically generate a protected procedure if you install auth as well

pranavp10 commented 1 month ago

@keegn are you able to fix the above error I am getting some new error

image
{
  "hasSrc": true,
  "packages": [
    "shadcn-ui",
    "drizzle",
    "next-auth",
    "trpc"
  ],
  "preferredPackageManager": "bun",
  "t3": false,
  "alias": "@",
  "analytics": true,
  "rootPath": "src/",
  "componentLib": "shadcn-ui",
  "driver": "pg",
  "provider": "postgresjs",
  "orm": "drizzle",
  "auth": "next-auth"
}