@trpc/next
TypeScript icon, indicating that this package has built-in type declarations

10.45.2 • Public • Published

tRPC

tRPC

End-to-end typesafe APIs made easy

Demo

@trpc/next

Connect a tRPC router to Next.js.

Documentation

Full documentation for @trpc/next can be found here

Installation

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

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

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

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

Basic Example

Setup tRPC in utils/trpc.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: true,
});

Hook up tRPC inside _app.tsx.

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.

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>;
}

Versions

Current Tags

Version History

Package Sidebar

Install

npm i @trpc/next

Homepage

trpc.io

Weekly Downloads

206,705

Version

10.45.2

License

MIT

Unpacked Size

111 kB

Total Files

57

Last publish

Collaborators

  • juliusmarminge
  • sachinraja
  • katt