node.jsgoogle-cloud-platformgoogle-cloud-sqlcloud-sql-proxy

How to Connect to Cloud SQL using Node.js?


Connecting to Cloud SQL using Node.js is not always straightforward.

Depending on the context, sometimes you have to connect to a Unix domain socket, allow-list IP addresses for TCP connections, run the Cloud SQL Auth proxy locally. Making these connections secure is yet another challenge: you might have to manage SSL certificates, firewalls rules, IP addresses, etc.

Is there a recommended way to Connect to Cloud SQL in a secure and easy way using Node.js?


Solution

  • Yes there indeed is, the Cloud SQL Node.js Connector, a Node.js package that makes connecting to Cloud SQL both easy and secure for all three supported database engines (Postgres, MySQL, and SQL Server), from anywhere (local machine, Cloud Run, App Engine, Cloud Functions, etc.)

    The Node.js Connector is one of the Cloud SQL connector libraries (also available in Python, Java and Go).

    How is a connector different from the other methods?

    The Cloud SQL connector libraries provide the following benefits:

    How do I use the Node.js Connector ... what does the code look like?

    Basic Usage (using pg)

    import pg from 'pg';
    import {Connector} from '@google-cloud/cloud-sql-connector';
    const {Pool} = pg;
    
    const connector = new Connector();
    const clientOpts = await connector.getOptions({
      instanceConnectionName: 'my-project:region:my-instance',
      ipType: 'PUBLIC', 
    });
    const pool = new Pool({
      ...clientOpts,
      user: 'my-user',
      password: 'my-password',
      database: 'db-name',
      max: 5
    });
    const {rows} = await pool.query('SELECT NOW()');
    console.table(rows); // prints returned time value from server
    
    await pool.end();
    connector.close();
    

    For further usage examples (MySQL, SQL Server, automatic IAM AuthN), please see the Cloud SQL Node.js Connector's detailed README.