CORS error on node tRPC server running in Google Cloud Run

217 views Asked by At

I have a node app running in Cloud Run whose main.ts looks like this:

import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { applyWSSHandler } from '@trpc/server/adapters/ws';
import { WebSocketServer } from 'ws';
import cors from 'cors';
import { AppRouter, appRouter } from './routers/app.router';
import { createContext } from './trpc';

// http server
const { server, listen } = createHTTPServer({
  middleware: cors(),
  router: appRouter,
  createContext
});

// ws server
const wss = new WebSocketServer({ server });
applyWSSHandler<AppRouter>({
  wss,
  router: appRouter,
  createContext
});

listen(8080);
console.log("tRPC listening on port 8080");

This all works fine when the API is running locally, but trying to call the API in Cloud Run results in CORS errors:

enter image description here

enter image description here

I thought it might be an HTTPS issue, and so I tried the following:

import cors from 'cors';
import { AppRouter, appRouter } from './routers/app.router';
import { createContext } from './trpc';
import * as fs from 'fs';
import * as trpcExpress from '@trpc/server/adapters/express';
import express from 'express';
import * as https from 'https';

const PORT = 8080;

const key = fs.readFileSync('/selfsigned.key');
const cert = fs.readFileSync('/selfsigned.crt');
const credentials = {
  key: key,
  cert: cert
};

const app = express();
app.use(cors());

app.use(
  '/',
  trpcExpress.createExpressMiddleware({
    router: appRouter,
    createContext
  })
);

const httpsServer = https.createServer(credentials, app);
httpsServer.listen(PORT);

I have just removed the websocket for the moment. This gives the same error though.

The service starts happily in Cloud Run, ...what might be the problem?

0

There are 0 answers