Create a TCP connection with SSL certificates when using Node.js

Open a TCP connection to Cloud SQL for MySQL by using the Node.js npm mysql module with SSL (Secure Sockets Layer) certificates.

Code sample


const createTcpPoolSslCerts = async config => {
  // Extract host and port from socket address
  const dbSocketAddr = process.env.DB_HOST.split(':');

  // Establish a connection to the database
  return mysql.createPool({
    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'
    host: dbSocketAddr[0], // e.g. ''
    port: dbSocketAddr[1], // e.g. '3306'
    ssl: {
      sslmode: 'verify-full',
      ca: fs.readFileSync(process.env.DB_ROOT_CERT), // e.g., '/path/to/my/server-ca.pem'
      key: fs.readFileSync(process.env.DB_KEY), // e.g. '/path/to/my/client-key.pem'
      cert: fs.readFileSync(process.env.DB_CERT), // e.g. '/path/to/my/client-cert.pem'
    // ... Specify additional properties here.

What's next

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