javascriptnext.jstrpc.io

Using tRPC for dynamic routes in NextJs


So I just started a small project using the full t3 stack (Nextjs, prisma, tailwind, tRPC), and have run into a small issue.

To give a little backstory, I have a database with artists (name, email, address, id, url) related to a "art" table (artName, artPrice, artDimensions) in pscale that I was going to pull in and make a page for based on their "url" at pages/artists/[url].tsx.

I set up a simple router under trpc/router/artist.ts:


export const artistRouter = router({

    // Find by id
    byUrl: publicProcedure
        .input(
            z.object({
                url: z.string(),
            })
        )
        .query(async ({ input }) => {
            const { url }  = input;
            const artist = await prisma.artist.findUnique({
                where: { url },
                select: defaultArtistSelect,
            });
            if (!dealer) {
            throw new TRPCError({
                code: 'NOT_FOUND',
                message: `No artist with url '${url}'`,
            });
        }
        return artist;
    }),

}

For my [url].tsx I know I can do the below to make a call and retrieve the data for the current page based on the url. However, this does cause a small "Loading" screen to occur since it is on the client and then the data populates (also the data is undefined on first query which another thing I havent wrapped my brain around).

const url = useRouter().query.url as string;
const { data: artist, isError, isLoading, isSuccess } = trpc.artist.byUrl.useQuery({ url });

I was hoping to SSR just the current route, but for the life of me I can not get getServerSideProps working with trpc. I could just use a prisma query to return the desired artist data, but I was trying to stick with trpc since I am doing client queries elsewhere (ie, admin views).

Is there a way to actually utilize getServerSideProps with trpc for a dynamic route?

** Update ** I completely missed the ssg helpers in the trpc docs which solved the getServerSideProps. Now it just seems really slow.


Solution

  • getServerSideProps() runs on the server, so you can do anything in it that you could anywhere else on the server. This means that the simplest way to call a tRPC procedure without using SSGHelpers is by extracting the procedure logic into a function and calling that. I recorded a video about this recently: https://www.youtube.com/watch?v=G2ZzmgShHgQ