The Cloud SQL Connectors are libraries that provide encryption and
Identity and Access Management (IAM)-based authorization when connecting to a
Cloud SQL instance. They can't provide a network path to a Cloud SQL
instance if one is not already present.
Using a Cloud SQL connector provides the following
benefits:
IAM authorization: Uses
IAM permissions to control who or
what can connect to your Cloud SQL instances.
Convenience: Removes the requirement to manage
SSL certificates, configure firewall rules, or enable authorized
networks.
Before you begin
Enable the Cloud SQL Admin API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM
role (roles/serviceusage.serviceUsageAdmin), which
contains the serviceusage.services.enable permission. Learn how to grant
roles.
The Cloud SQL Java Connector is a library that provides
IAM-based authorization and encryption when connecting to a
Cloud SQL instance. It can not provide a network path to a
Cloud SQL instance if one is not already present.
Install
For instructions on building and using the drivers for JDBC and R2DBC
with the Cloud SQL Java Connector, see the following links:
To activate credentials locally, use the following
gcloud command:
gcloudauthapplication-defaultlogin
Connect with Intellij
In order to connect IntelliJ
to your Cloud SQL instance, you will need to add the library as a jar with dependencies in the
Additional Files section on the driver settings page. For example, prebuilt fat jars can be found on the
Cloud SQL Java Connector Releases
page for this purpose.
Python
The Cloud SQL Python Connector is a library that can be used alongside a
database driver to allow users with sufficient permissions to connect to a
Cloud SQL database without having to manually allowlist IPs or manage
SSL certificates.
To activate credentials locally, use the following
gcloud command:
gcloudauthapplication-defaultlogin
Go
The Cloud SQL Go connector is a Cloud SQL connector designed for use with
the Go language. For improved security, this connector uses robust,
manually authenticated TLS 1.3 encryption between the client connector
and the server-side proxy, independent of the database protocol.
Install
You can install this repo with go get:
gogetcloud.google.com/go/cloudsqlconn
Node.js
The Node.js Connector is a library designed for use with the Node.js
runtime that allows you to connect securely to your Cloud SQL instance.
Install
You can install the library with npm install:
npminstall@google-cloud/cloud-sql-connector
Use
Java
To see this snippet in the context of a web application, view
the README on GitHub.
importcom.zaxxer.hikari.HikariConfig;importcom.zaxxer.hikari.HikariDataSource;importjavax.sql.DataSource;publicclassConnectorConnectionPoolFactoryextendsConnectionPoolFactory{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.privatestaticfinalStringINSTANCE_CONNECTION_NAME=System.getenv("INSTANCE_CONNECTION_NAME");privatestaticfinalStringDB_USER=System.getenv("DB_USER");privatestaticfinalStringDB_PASS=System.getenv("DB_PASS");privatestaticfinalStringDB_NAME=System.getenv("DB_NAME");publicstaticDataSourcecreateConnectionPool(){// The configuration object specifies behaviors for the connection pool.HikariConfigconfig=newHikariConfig();// The following is equivalent to setting the config options below:// jdbc:sqlserver://;user=<DB_USER>;password=<DB_PASS>;databaseName=<DB_NAME>;// socketFactoryClass=com.google.cloud.sql.sqlserver.SocketFactory;// socketFactoryConstructorArg=<INSTANCE_CONNECTION_NAME>// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url// Configure which instance and what database user to connect with.config.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");config.setUsername(DB_USER);// e.g. "root", "sqlserver"config.setPassword(DB_PASS);// e.g. "my-password"config.addDataSourceProperty("databaseName",DB_NAME);config.addDataSourceProperty("socketFactoryClass","com.google.cloud.sql.sqlserver.SocketFactory");config.addDataSourceProperty("socketFactoryConstructorArg",INSTANCE_CONNECTION_NAME);// The Java Connector provides SSL encryption, so it should be disabled// at the driver level.config.addDataSourceProperty("encrypt","false");// cloudSqlRefreshStrategy set to "lazy" is used to perform a// refresh when needed, rather than on a scheduled interval.// This is recommended for serverless environments to// avoid background refreshes from throttling CPU.config.addDataSourceProperty("cloudSqlRefreshStrategy","lazy");// ... Specify additional connection properties here.// ...// Initialize the connection pool using the configuration object.returnnewHikariDataSource(config);}}
Python
See
How to use this Connector for detailed instructions on using the library. View example connection test code on GitHub.
importosfromgoogle.cloud.sql.connectorimportConnector,IPTypesimportpytdsimportsqlalchemydefconnect_with_connector()-> sqlalchemy.engine.base.Engine:""" Initializes a connection pool for a Cloud SQL instance of SQL Server. Uses the Cloud SQL Python Connector package. """# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.instance_connection_name=os.environ["INSTANCE_CONNECTION_NAME"]# e.g. 'project:region:instance'db_user=os.environ.get("DB_USER","")# e.g. 'my-db-user'db_pass=os.environ["DB_PASS"]# e.g. 'my-db-password'db_name=os.environ["DB_NAME"]# e.g. 'my-database'ip_type=IPTypes.PRIVATEifos.environ.get("PRIVATE_IP")elseIPTypes.PUBLIC# initialize Cloud SQL Python Connector objectconnector=Connector(ip_type=ip_type,refresh_strategy="LAZY")connect_args={}# If your SQL Server instance requires SSL, you need to download the CA# certificate for your instance and include cafile={path to downloaded# certificate} and validate_host=False. This is a workaround for a known issue.ifos.environ.get("DB_ROOT_CERT"):# e.g. '/path/to/my/server-ca.pem'connect_args={"cafile":os.environ["DB_ROOT_CERT"],"validate_host":False,}defgetconn()-> pytds.Connection:conn=connector.connect(instance_connection_name,"pytds",user=db_user,password=db_pass,db=db_name,**connect_args)returnconnpool=sqlalchemy.create_engine("mssql+pytds://",creator=getconn,# ...)returnpool
Go
See
Usage for detailed instructions on using the library. View example connection test code on GitHub.
packagecloudsqlimport("context""database/sql""fmt""log""net""os""cloud.google.com/go/cloudsqlconn"mssql"github.com/denisenkom/go-mssqldb")typecsqlDialerstruct{dialer*cloudsqlconn.DialerconnNamestringusePrivatebool}// DialContext adheres to the mssql.Dialer interface.func(c*csqlDialer)DialContext(ctxcontext.Context,network,addrstring)(net.Conn,error){varopts[]cloudsqlconn.DialOptionifc.usePrivate{opts=append(opts,cloudsqlconn.WithPrivateIP())}returnc.dialer.Dial(ctx,c.connName,opts...)}funcconnectWithConnector()(*sql.DB,error){mustGetenv:=func(kstring)string{v:=os.Getenv(k)ifv==""{log.Fatalf("Fatal Error in connect_connector.go: %s environment variable not set.\n",k)}returnv}// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.var(dbUser=mustGetenv("DB_USER")// e.g. 'my-db-user'dbPwd=mustGetenv("DB_PASS")// e.g. 'my-db-password'dbName=mustGetenv("DB_NAME")// e.g. 'my-database'instanceConnectionName=mustGetenv("INSTANCE_CONNECTION_NAME")// e.g. 'project:region:instance'usePrivate=os.Getenv("PRIVATE_IP"))dbURI:=fmt.Sprintf("user id=%s;password=%s;database=%s;",dbUser,dbPwd,dbName)c,err:=mssql.NewConnector(dbURI)iferr!=nil{returnnil,fmt.Errorf("mssql.NewConnector: %w",err)}// WithLazyRefresh() Option is used to perform refresh// when needed, rather than on a scheduled interval.// This is recommended for serverless environments to// avoid background refreshes from throttling CPU.dialer,err:=cloudsqlconn.NewDialer(context.Background(),cloudsqlconn.WithLazyRefresh())iferr!=nil{returnnil,fmt.Errorf("cloudsqlconn.NewDailer: %w",err)}c.Dialer=&csqlDialer{dialer:dialer,connName:instanceConnectionName,usePrivate:usePrivate!="",}dbPool:=sql.OpenDB(c)iferr!=nil{returnnil,fmt.Errorf("sql.Open: %w",err)}returndbPool,nil}
Node.js
For detailed instructions on using the library, see
Usage.
const{Connection}=require('tedious');const{Connector}=require('@google-cloud/cloud-sql-connector');// In case the PRIVATE_IP environment variable is defined then we set// the ipType=PRIVATE for the new connector instance, otherwise defaults// to public ip type.constgetIpType=()=>
process.env.PRIVATE_IP==='1'||process.env.PRIVATE_IP==='true'?'PRIVATE':'PUBLIC';// connectWithConnector initializes a TCP connection// to a Cloud SQL instance of SQL Server.constconnectWithConnector=asyncconfig=>{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.constconnector=newConnector();constclientOpts=awaitconnector.getTediousOptions({instanceConnectionName:process.env.INSTANCE_CONNECTION_NAME,ipType:getIpType(),});constdbConfig={// Please note that the `server` property here is not used and is only// defined due to a bug in the tedious driver// (ref: https://github.com/tediousjs/tedious/issues/1541)// With that in mind, do not try to change this value since it will have no// impact in how the connector works, this sample will be updated to remove// this property declaration as soon as the tedious driver bug is fixedserver:'0.0.0.0',// e.g. '127.0.0.1'authentication:{type:'default',options:{userName:process.env.DB_USER,// e.g. 'my-db-user'password:process.env.DB_PASS,// e.g. 'my-db-password'},},options:{...clientOpts,// Please note that the `port` property here is not used and is only// defined due to a bug in the tedious driver// (ref: https://github.com/tediousjs/tedious/issues/1541)// With that in mind, do not try to change this value since it will have// no impact in how the connector works, this sample will be updated to// remove this property declaration as soon as the tedious driver bug is// fixedport:9999,database:process.env.DB_NAME,// e.g. 'my-database'useColumnNames:true,},// ... Specify additional properties here....config,};// Establish a connection to the database.returnnewConnection(dbConfig);};
Enforce
By using connector enforcement, you can enforce using only the Cloud SQL Auth Proxy or Cloud SQL Language Connectors to connect to Cloud SQL instances. With connector enforcement, Cloud SQL rejects direct connections to the database.
If you're using a Private Service Connect-enabled instance, then there's a limitation. If the instance has connector enforcement enabled, then you can't create read replicas for the instance. Similarly, if the instance has read replicas, then you can't enable connector enforcement for the instance.
gcloud
To enforce using only the Cloud SQL Auth Proxy or Cloud SQL Language Connectors to connect to an instance, use the gcloud sql instances patch command:
Make sure you are using the latest version of the Cloud SQL Connectors
and your database driver to avoid incompatibilities. Some older versions
of drivers are not supported.
Connection paths
The Cloud SQL Connectors provide authorization for connections, but they
don't provide new paths to connectivity. For example, in order to
connect to a Cloud SQL instance using a Private IP address, your
application must already have VPC access.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-06-11 UTC."],[],[]]