Cannot Figure Out CORS using Node Serverless Functions

Site Name: https://not-another-mug.netlify.app/
Repo: Bitbucket

Here’s my api.ts file:

import express from “express”;
import serverless from “serverless-http”;
import router from “…/my/path/file.js”;
import type { HandlerContext, HandlerEvent } from “@netlify/functions”;

export async function handler(event: HandlerEvent, context: HandlerContext) {
const app = express();

app.use("/api/list", router);

return serverless(app)(event, context);

}

I set this up just like the Netlify docs said. The problem is that when I make a call from my React app (which is on another site but same Netlify account), the call hangs for about 10s and gives me a 502 error saying that I have a CORS issue.

I tried using the cors npm package, adding response headers to an options variable and passing it into the serverless function, and a few other things to no avail. What am I doing wrong?

FYI: The page with the issue is the dashboard page which won’t make a call unless you’re logged in. If you don’t want to log in, I can update code to work without logging in.

Add app.use(cors()) after this snippet which should enable CORS in your app.

I feel like I tried that already but I’ll do it again and see what happens.

…well, I had it before the snippet. I’ll add it after this time.

@SamO Still not working. Here’s my api.ts file:

import express from “express”;
import serverless from “serverless-http”;
import listRouter from “…/…/…/server/src/routes/lists.js”;
import type { HandlerContext, HandlerEvent } from “@netlify/functions”;
import cors from “cors”;

export async function handler(event: HandlerEvent, context: HandlerContext) {
const netlifyApi = express();

netlifyApi.use(“/api/list”, listRouter);

const corsOptions = {
“origin”: [“https://not-another-mug.netlify.app”],
“methods”: “GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS”,
“preflightContinue”: false,
“optionsSuccessStatus”: 200,
“credentials”: false
};

netlifyApi.use(cors(corsOptions));

return serverless(netlifyApi)(event, context);
}

CORS has nothing to do with Netlify. Please use Netlify Rewrites: Rewrites and proxies | Netlify Docs to trick the browser into thinking it’s a same origin request.