CORS Error: Why You Can't Call an API Directly from a Vue/React Frontend
Getting blocked by CORS when writing Fetch requests to an API on the frontend? A deep dive into the browser same-origin policy and the enormous risk of leaking your API key in plaintext on the frontend, plus guidance on building a minimal backend relay layer.
1. Why does Google's official API directly prohibit frontend cross-origin requests?
Many beginners write fetch('https://generativelanguage...') directly in a Vue or React component, and the console immediately fills with red Access-Control-Allow-Origin CORS errors.
This is a defensive design that Google deliberately implements for security reasons!
If you call it directly in frontend JavaScript, any visitor only needs to press F12 to extract your API key directly from the source code and abuse it without restraint.
2. Standard Development Pattern
You must write a lightweight endpoint in a backend such as Node.js, Next.js API Routes, or FastAPI, read environment variables in a secure backend environment, and make requests to Google. The frontend only communicates with your own backend server.