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

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

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.

Question:

  • I need to use a free AI API to perform some computations. If there is any better way to handle this, I would appreciate a good explanation along with code examples.

How can I resolve this CORS issue, or what am I missing here? And if there’s a better way to securely use AI APIs (like free ones), please provide a solution with code.

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.