Using API Keys to send Cloud SQL Queries in JavaScript

I am trying to service a public website from a Google Cloud SQL database (MySQL).

Since it is a public website, I found out the only way for me to gain access in to use an API Key, and add it it to the request like that: ...?key=FHkdvfio.....

If I understand correctly, the Cloud SQL DB end point should look something like that:

jdbc:google:mysql://<my-instance-ip>:3306/<my-database-name>?key=....

What I could not find, is an example of how to actually send SQL queries from JavaScript using this API Key.

The reason I’m using JavaScript is because the web client is actually Google Apps Script driving a Google Sheet, with its pre-cursor JavaScript language.

Since it is a PUBLIC, ANONYMOUS website, I cannot use any of the Google provided libraries for Apps Script or connection/authentication methods, as the end user is not known, nor identified or logged-into any known Google account from any known IP address. Hence, the API Key method.

Can anyone point me in the right directions please?

Answer

In short; you shouldn’t do this as it is an insecure practice and API keys are unsupported by the MySQL database engine. You generally don’t want to allow public access even to connect to your database, as it can expose security risks.

Typically, websites handle this by using API calls to the backend server, which are authenticated in some way. You could replicate this pattern by hosting your own service (perhaps in Cloud Functions or Cloud Run) that authenticates requests and performs queries needed to the instance.

Alternatively, consider using a managed service (perhaps Firestore) that does have this functionality. Firestore will also be “pay for what you use”, meaning it’s cost will scale with your traffic.