Issue with CORS when hitting API using LangChain.js with MERN stack [duplicate]


I am using LangChain.js in my MERN stack project and I am importing the following:

import { ChatGoogleGenerativeAI } from "@langchain/google-genai";

Scenario:

  • In my frontend, I am hitting an API endpoint /llm/response which is supposed to interact with Google AI via LangChain.

  • The issue I am facing is that from the frontend I get a CORS error, something like:

    Access to XMLHttpRequest at ‘http://localhost:3000/api/llm/response’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. `.

  • However, when I test the same API endpoint separately using Postman, it works fine and gives me a response.

Additional observations:

  • When I directly interact with Google AI via LangChain.js from the frontend, it works without any CORS issue, but my API key gets exposed, which is a security risk.

  • I created another endpoint in the backend called /test to check CORS from the frontend through this endpoint, and it gives no error and works fine. So, I don’t think this is a typical CORS error.

Question:

How can I resolve this CORS issue, or what am I missing here?

What I tried and what I was expecting:

  • I tried hitting the /llm/response endpoint from my frontend expecting it to work just like it does in Postman without CORS issues, but instead, I got a CORS error.
  • I also tried setting up a backend proxy to resolve the issue, but it didn’t work. I expected that hitting the API from the frontend would securely interact with the API without exposing my API key.