BattlePoap
BattlePoap

Reputation: 41

React Vite turbo Monorepo + tRPC, Prisma : Cors Pre-flight error when deploying to Vercel

I am new with monorepos and deployment, and used this boilerplate template to start a project: https://github.com/noahflk/react-trpc-turbo

Everything works fine in dev mode and front was doing ok in Vercel with local data before implementing the api, so I wanted to try my hand at deploying the server.

I am getting this error in Chrome, with my front : enter image description here

Fun fact, going to the server I got this : enter image description here, which is my index.ts (start command should use serve.ts) (see architecture bellow)

Vercel Front env :

(front worked alright before server implementation - I just added the following env variables) enter image description here

Monorepo architecture:

enter image description here

Server.ts :

import { createExpressMiddleware } from '@trpc/server/adapters/express';
import cors from 'cors';
import 'dotenv/config';
import express from 'express';

import { appRouter } from '@api/router';

async function main() {
  const port = process.env.PORT || 3000;

  const app = express();

  const corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }
  
  app.use(cors(corsOptions));

  app.use(
    '/trpc',
    createExpressMiddleware({
      router: appRouter,
      createContext: (ctx) => ({ req: ctx.req, res: ctx.res }),
      onError:
        process.env.NODE_ENV === 'development'
          ? ({ path, error }) => {
              console.error(`❌ tRPC failed on ${path ?? '<no-path>'}: ${error.message}`);
            }
          : undefined,
    })
  );

  // For testing purposes, wait-on requests '/'
  app.get('/', (req, res) => res.send('Server is running now!'));

  app.listen(port, () => {
    console.log(`App listening on port: ${port}`);
  });
}

void main();

Router.ts

import { helloRouter } from '@api/router/hello';
import { router } from '@api/trpc';
import { spellsRouter } from './spells';

export const appRouter = router({
  hello: helloRouter,
  spells: spellsRouter,
});

export type AppRouter = typeof appRouter;

Vercel server deployment settings :

.env variable DATABASE_URL (mongodb) set as string without " " in Vercel deployment settings. enter image description here

Upvotes: 0

Views: 93

Answers (0)

Related Questions