Getting Started with tRPC in Next.js

Ha Doan
2 min readMay 2, 2024

tRPC is a fantastic tool that allows developers to create typesafe APIs. It is an end-to-end typesafe API framework for Next.js. If youre new to tRPC and Next.js, this step-by-step guide is the perfect place to get started.

Step 1: Setup Your Next.js Project

Firstly, you need to have a Next.js project set up. If you dont have one yet, you can create a new one using the following command:

npx create-next-app@latest

Step 2: Install the tRPC Packages

With your Next.js project set up, its time to install tRPC. Run the following command:

npm install @trpc/client @trpc/server @trpc/react @trpc/next

These packages provide the client, server, and React integrations, as well as the Next.js adapters for tRPC.

Step 3: Create Your First tRPC Router

Create a new file at `pages/api/trpc/[trpc].ts`:

import { createRouter } from @trpc / server;
import { TRPCResponse } from @trpc / server;
import { NextApiRequest, NextApiResponse } from next;
export default createRouter()
.query(getHello, {
resolve() {
return Hello tRPC;
},
})
.createNextServer({
getHTTPContext: ({ req, res }: { req: NextApiRequest; res: NextApiResponse }) => ({
req,
res,
}),
})

In this file, weve defined a simple tRPC router with a single query: `getHello`. When this query is called, it will return the string Hello tRPC.

Step 4: Set Up Your tRPC Client

Now, lets set up the tRPC client. This will be used to call the API we just created. Create a new file at `utils/trpc.ts`:

import { createTRPCClient } from @trpc/client;
import { AppRouter } from ../pages/api/trpc/[trpc];
export const client = createTRPCClient<AppRouter>({
url: http://localhost:3000/api/trpc,
});

Here, weve created a tRPC client that points to our API endpoint.

Step 5: Use Your tRPC API in a Component

Finally, lets use our `getHello` API in a component. Create a new file at `pages/index.tsx`:

import { client } from ../utils/trpc;
import { useEffect, useState } from react;
export default function Home() {
const [message, setMessage] = useState();
useEffect(() => {
client.query(getHello).then(setMessage);
}, []);
return <div>{message}</div>;
}

Here, were calling our `getHello` API on component mount and displaying the returned message.

And voila! Youve now successfully set up a typesafe API with tRPC and Next.js. Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response