A super simple minimal tRPC for next-js

Overview

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 need the full functionality of tRPC.

Installation

npm install next-ts-routes

yarn install next-ts-routes

pnpm install next-ts-routes

Usage

This is an example of how to use next-ts-routes

Add the next wrapper

// next.config.js
const withNextTsRoutes = require('next-ts-routes/withNextTsRoutes')

module.exports = withNextTsRoutes({})
next.config.mjs
// next.config.mjs
import { env } from "./src/env/server.mjs";
import { withNextTsRoutes } from 'next-ts-routes/withNextTsRoutes';

/**
 * Don't be scared of the generics here.
 * All they do is to give us autocompletion when using this.
 *
 * @template {import('next').NextConfig} T
 * @param {T} config - A generic parameter that flows through to the return type
 * @constraint {{import('next').NextConfig}}
 */
function defineNextConfig(config) {
  return withNextTsRoutes(config);
}

export default defineNextConfig({
});

Ignoring other server side only modules

For the time being this is a hacky way to achieve this, will ideally fine a better way in the future.

// next.config.js
const withNextTsRoutes = require('next-ts-routes/withNextTsRoutes')

module.exports = withNextTsRoutes({}, {
  fs: false
})

Basic Usage

You can see an example with typescript intellisense here - https://stackblitz.com/edit/typescript-qbv1tp?file=index.ts

// api/clip.ts
import { route } from "next-ts-routes";

const { handler, get, post } = route("api/clip", {
  ctx: async () => {
    const Redis = (await import("@upstash/redis")).Redis;

    const redis = new Redis();

    return { redis };
  },
  GET: async ({}, { ctx }) => {
    return ctx.redis.get("clip") as Promise<string | undefined>;
  },
  POST: async ({ input }: { input: { text: string } }, { ctx }) => {
    return ctx.redis.set("clip", input.text);
  },
});

export const getClip = get;
export const postClip = post;

export default handler;

Note: As this file is directly imported in the browser, you cannot use any nodejs specific imports, like fs or path globally. You should dynamically import them and then use them.

Now you can import the getClip and postClip functions and use them in your app.

// pages/index.tsx
import { getClip, postClip } from '../api/clip';

export default function Home() {
  const [clip, setClip] = useState<string | undefined>(undefined);

  useEffect(() => {
    getClip().then(setClip);
  }, []);

  return (
    <div>
      <h1>Clip</h1>
      <p>{clip}</p>
      <form
        onSubmit={async (e) => {
          e.preventDefault();
          const text = e.currentTarget.elements[0].value;
          await postClip({ text });
          setClip(text);
        }}
      >
        <input type="text" />
        <button type="submit">Set</button>
      </form>
    </div>
  );
}

This can totally be used with swr or react-query as well for nice hooks, will write some docs for this later

You might also like...

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

Jan 8, 2023

Prisma +2 generator to emit a tRPC shield from your Prisma schema

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

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

Aug 30, 2022

tRPC test & precursor to a billion dollar social cat network

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

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

Jan 9, 2023

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
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
NX monorepo showing the TMDB Watchlist mobile app with Expo, tRPC, Next, and Prisma

tmdb-watchlist-prisma This app uses TMDB to retrieve a list of Now Playing movies. You can add/remove movies to track which ones you've watched. There

Mat Warger 65 Dec 28, 2022
Kaol Stack - Prisma, Expo, Next, TRPC, Solito, Tailwind - A monorepo template for a truly universal app

Kaol Stack ?? About A monorepo with Prisma, Next.js, Expo, tRPC, Authentication and Solito setup and configured to work together. With this setup you

Matheus Vicente 187 Dec 21, 2022
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
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
Super minimal selector and event library

min.js A super tiny JavaScript library to execute simple DOM querying and hooking event listeners. Aims to return the raw DOM node for you to manipula

Remy Sharp 1.1k Dec 13, 2022
Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics.

Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics. Includes tags/categories support and extensive features for code blocks such as live preview, line numbers, and line highlighting.

Priya Chakraborty 0 Jan 29, 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