tRPC + Next.js

Overview

next-trpc

A drop-in version of tRPC + Next.js.

If you haven't seen tRPC before, it's an excellent Next.js-native solution vs a traditional REST or GraphQL interface.

Fast, easy and fully-typed - it's hard to beat for an all-Javascript stack.

Quickstart

Install next-trpc and dependencies:

npm i next-trpc

Create the tRPC endpoint at ./pages/api/trpc/[trpc].ts

import { trpc, nextTRPC } from "next-trpc"

import contracts from "../../../trpc/routers/contracts"
import lists from "../../../trpc/routers/lists"
import wallets from "../../../trpc/routers/wallets"

export const router = trpc.router({
  hello: trpc.procedure
    .input(
      object({
        name: string().required()
      })
    )
    .query(async ({ input }) => {
      return `Hello, ${input.name}`
    })
})

// this needs to be exported so your client can extend type defs
export type Router = typeof router

export default nextTRPC({
  router
})

Use tRPC in your pages/components:

import { Router } from "../pages/api/trpc/[trpc]"
import { createClient } from "next-trpc/client"

export const client = createClient<Router>()

const Component = () => {
  const { data: msg } = client.hello.useQuery({
    name: "Ian H"
  })

  return <div>{msg}</div>
}

And you're done! Read more on how to use tRPC at https://trpc.io/.

Examples

Custom Authentication header

Add the context handler to your API endpoint in ./pages/api/trpc/[trpc].ts

import { trpc, nextTRPC } from "next-trpc"

export type Context = {
  auth?: {
    address: string
  }
}

export const context = async ({ req }): Promise<Context> => {
  if (req.headers.authorization) {
    const token = req.headers.authorization.split(" ")[1]
    const auth = // do something with your auth header
    return {
      auth
    }
  }

  return {}
}

export default nextTRPC({
  createContext: context,
  router
})

Then set the Authorization header in your client:

import { createClient } from "next-trpc/client"
import { Router } from "../pages/api/trpc/[trpc]"
import { getToken } from "../your/token/utils"

const client = createClient<Router>({
  headers: () => {
    const token = getToken()
    return {
      Authorization: token ? `Bearer ${token}` : ""
    }
  }
})

Split routers into multiple files

You can use the exported { trpc } however you would with a standalone tRPC setup:

const hello = trpc.router({
  get: trpc.procedure
    .input(
      object({
        name: string().required()
      })
    )
    .query(async ({ input }) => {
      return `Hello, ${input.name}`
    })
})

const another = trpc.router({
  get: trpc.procedure.query(async ({ input }) => {
    return `I'm another endpoint`
  })
})

const router = trpc.router({
  hello,
  another
})

export default nextTRPC({
  router
})
You might also like...

Scaffold a full-stack SvelteKit application with tRPC and WindiCSS out of the box

create-sweet-app Interactive CLI to quickly set up an opinionated, full-stack, typesafe SvelteKit project. Inspired by the T3 Stack and create-t3-app

Dec 16, 2022

A trpc-ified useReducer hook. ⚡

trpc-reducer A trpc-ified react useReducer hook that lets you perform state logic in reducers just like React's useReducer hook When you dispatch an a

Aug 27, 2022

Qwik City adapter for trpc.io

Qwik City adapter for trpc.io

tRPC 🤝 Qwik City End-to-end typesafe APIs made easy with tRPC.io in Qwik City applications. Build & consume fully typesafe APIs, without schemas or c

Oct 11, 2022

A fullstack TikTok clone with Nextjs, Prisma, trpc

TikTok Clone A fullstack TikTok clone with Nextjs, Prisma, trpc Live demo Official website: https://toptop-clone.vercel.app/ Main technology used The

Dec 19, 2022

🖼️ Image proxy for Next.js. Makes it possible to use dynamic domains in next/image component.

Next.js Image Proxy Image proxy for Next.js. Makes it possible to use dynamic domains in next/image component. ❔ Motivation This library makes it poss

Dec 1, 2022

next-graphql-server is a library for building production-grade GraphQL servers using Next.js with API Routes

next-graphql-server next-graphql-server is an easy to use Next.js library for creating performant GraphQL endpoints on top of Next.js API Routes. Star

Nov 21, 2022

💻 A simple Create Next App template to start your projects with Next.js, TypeScript, ESLint, Prettier and other tools.

⚡ Next Typescript Template ⚡ A simple Create Next App template to start your projects with Next.js, TypeScript, ESLint, Prettier and other tools. Quic

Nov 23, 2022

A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui

A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui

Welcome to FullStack Next.js template 👋 A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui ✨ Demo Tech Ne

Oct 16, 2022

This is a Next.js project bootstrapped with create-next-app.

Getting Started First, run the development server: npm run dev # or yarn dev Open http://localhost:3000 with your browser to see the result. You can s

Dec 5, 2022
Owner
ianh.eth
React / web3 Developer. Building @mintdrop-xyz
ianh.eth
Next.js + tRPC + Blitz.js Auth + Prisma. Fullstack app example

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Daiki Okumura 6 Oct 12, 2022
A super simple minimal tRPC for next-js

Typed Routes A way to have fully typed routes in next, without all the complexity of tRPC. This is more for super minimal use cases, where you don't n

Rahul Tarak 4 Dec 28, 2022
tRPC + Next.js

next-trpc A drop-in version of tRPC + Next.js. If you haven't seen tRPC before, it's an excellent Next.js-native solution vs a traditional REST or Gra

ianh.eth 5 Dec 21, 2022
End-to-end typesafe APIs with tRPC.io in SvelteKit applications

✨ tRPC-SvelteKit End-to-end typesafe APIs with tRPC.io in SvelteKit applications. No code generation, run-time bloat, or build pipeline. ❤️ ???? See b

Ionut-Cristian Florescu 307 Dec 29, 2022
Prisma 2+ generator to emit fully implemented tRPC routers

Prisma tRPC Generator Automatically generate fully implemented tRPC routers from your Prisma Schema. This includes routers, app router and of course a

Omar Dulaimi 370 Jan 3, 2023
tRPC-ified SWR hooks

trpc-swr tRPC-ified SWR hooks Installation npm install trpc-swr @trpc/client Usage First, create your fully typed hooks using your router type: // trp

Sachin Raja 129 Jan 8, 2023
Prisma +2 generator to emit a tRPC shield from your Prisma schema

Prisma tRPC Shield Generator Automatically generate a tRPC Shield from your Prisma Schema. Updates every time npx prisma generate runs. Table of Conte

Omar Dulaimi 27 Dec 24, 2022
Proof of concept: support immutable trpc servers using lambdas to ensure client/server compatibility

auto-versioned-trpc-aws-lambda Proof of concept to support an automatically versioned AWS Lambda running tRPC to ensure a somewhat graceful and automa

Kenneth Skovhus 5 Aug 30, 2022
tRPC test & precursor to a billion dollar social cat network

CatMash What is this? Have you ever wanted to rank 11,000 cat pictures by cuteness? Of course you have. That's what we're doing here. This is an app b

Christopher Ehrlich 6 Dec 18, 2022
OpenAPI support for tRPC 🧩

trpc-openapi OpenAPI support for tRPC ?? Easy REST endpoints for your tRPC procedures. Perfect for incremental adoption. OpenAPI version 3.0.3. Usage

James Berry 841 Jan 9, 2023