Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Created September 23, 2022 01:07
Show Gist options
  • Save tatsuyasusukida/5e527a86e7131b4f34f48ac1430ba882 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/5e527a86e7131b4f34f48ac1430ba882 to your computer and use it in GitHub Desktop.
Next.js tRPC example
import { initTRPC } from "@trpc/server";
import * as trpcNext from "@trpc/server/adapters/next";
import { z } from "zod";
export const t = initTRPC.create()
export const appRouter = t.router({
hello: t.procedure
.input(z.object({
text: z.string(),
}))
.query(({ input }) => {
return {
greeting: `Hello ${input.text}`,
}
})
})
export type AppRouter = typeof appRouter
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext: () => ({}),
})
import type { AppProps } from 'next/app'
import '../styles/globals.css'
import { trpc } from '../utils/trpc'
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default trpc.withTRPC(MyApp)
import { NextPage } from "next";
import { trpc } from "../utils/trpc";
const Client: NextPage = () => {
const hello = trpc.hello.useQuery({ text: 'tRPC' })
return (
<main>
{hello.data?.greeting}
</main>
)
}
export default Client
import { createTRPCNext } from '@trpc/next'
import { httpBatchLink } from '@trpc/client'
import { AppRouter } from '../pages/api/trpc/[trpc]'
export const trpc = createTRPCNext<AppRouter>({
config({ ctx }) {
return {
links: [
httpBatchLink({
url: '/api/trpc',
}),
],
}
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment