Back to Trpc

`@trpc/next`

packages/next/README.md

11.16.02.0 KB
Original Source
<p align="center"> <a href="https://trpc.io/"></a> </p> <h3 align="center">tRPC</h3> <p align="center"> <strong>End-to-end typesafe APIs made easy</strong> </p> <p align="center"> </p>

@trpc/next

Connect a tRPC router to Next.js.

Documentation

Full documentation for @trpc/next can be found here

Installation

bash
# npm
npm install @trpc/next @trpc/react-query @tanstack/react-query

# Yarn
yarn add @trpc/next @trpc/react-query @tanstack/react-query

# pnpm
pnpm add @trpc/next @trpc/react-query @tanstack/react-query

# Bun
bun add @trpc/next @trpc/react-query @tanstack/react-query

AI Agents

If you use an AI coding agent, install tRPC skills for better code generation:

bash
npx @tanstack/intent@latest install

Basic Example

Setup tRPC in utils/trpc.ts.

ts
import { createTRPCNext, httpBatchLink } from '@trpc/next';
// Import the router type from your server file
import type { AppRouter } from '../pages/api/[trpc].ts';

export const trpc = createTRPCNext<AppRouter>({
  config() {
    return {
      links: [
        httpBatchLink({
          url: 'http://localhost:3000/trpc',
        }),
      ],
    };
  },
  ssr: false,
});

Hook up tRPC inside _app.tsx.

ts
import { trpc } from '~/utils/trpc';

const App = ({ Component, pageProps }) => {
  return <Component {...pageProps} />;
};

export default trpc.withTRPC(App);

Now you can query your API in any component.

ts
import { trpc } from '~/utils/trpc';

export function Hello() {
  const { data, error, status } = trpc.greeting.useQuery({
    name: 'tRPC',
  });

  if (error) {
    return <p>{error.message}</p>;
  }

  if (status !== 'success') {
    return <p>Loading...</p>;
  }

  return <div>{data && <p>{data.greeting}</p>}</div>;
}

Server components

See https://trpc.io/docs/client/react/server-components