sachinraja / trpc-playground

playground for running tRPC queries in the browser
MIT License
281 stars 19 forks source link

Usage with standalone trpc adapter #45

Closed Hellrasier closed 1 year ago

Hellrasier commented 1 year ago

How to use this playground with standalone trpc server?

MatsDK commented 1 year ago

After some trying I got it to work.

import { createHTTPHandler } from '@trpc/server/adapters/standalone';
import { createServer } from 'http';
import { nodeHandler } from "trpc-playground/handlers/node";

// define your router here...

const playgroundEndpoint = '/playground';

(async () => {
  const trpcHandler = createHTTPHandler({
    router,
    createContext() {
      return {};
    },
  });

  const playgroundHandler = await nodeHandler({
    playgroundEndpoint,
    router,
    trpcApiEndpoint: "http://localhost:3333",
  })

  createServer((req, res) => {
    if (req.url?.startsWith(playgroundEndpoint)) {
      playgroundHandler(req, res)
    } else {
      trpcHandler(req, res);
    }
  }).listen(3333, () => {
    console.log("> Trpc server listening on http://localhost:3333")
    console.log("> Trpc playground listening on http://localhost:3333/playground")
  });
})()

This solution is hacky, but I hope it helps you.