Create a TCP connection when using Node.js

Open a TCP connection to Cloud SQL for MySQL by using the Node.js npm mysql module.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


To authenticate to Cloud SQL for MySQL, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const mysql = require('promise-mysql');
const fs = require('fs');

// createTcpPool initializes a TCP connection pool for a Cloud SQL
// instance of MySQL.
const createTcpPool = async config => {
  // Note: Saving credentials in environment variables is convenient, but not
  // secure - consider a more secure solution such as
  // Cloud Secret Manager ( to help
  // keep secrets safe.
  const dbConfig = {
    host: process.env.INSTANCE_HOST, // e.g. ''
    port: process.env.DB_PORT, // e.g. '3306'
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // ... Specify additional properties here.
  // Establish a connection to the database.
  return mysql.createPool(dbConfig);

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.