Skip to content

@trpc/server - Handling CORS and CORS preflight requests #655

Answered by KATT
lleyton asked this question in Q&A
Discussion options

You must be logged in to vote

You can use the http handler straight-off.

Example code

import * as trpc from '@trpc/server';
import { z } from 'zod';
import http from 'http';

type Context = {};

export const appRouter = trpc.router<Context>().query('hello', {
  input: z
    .object({
      name: z.string(),
    })
    .optional(),
  resolve: ({ input }) => {
    return {
      text: `hello ${input?.name ?? 'world'}`,
    };
  },
});

export type AppRouter = typeof appRouter;

// create handler
const handler = trpc.createHttpHandler({
  router: appRouter,
  createContext() {
    return {};
  },
});

const server = http.createServer((req, res) => {
  // do whatever you want here
  // Set CORS headers
  res.setHeader('Ac…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@wiredmatt
Comment options

Answer selected by KATT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #623 on July 12, 2021 23:04.