How to securely connect to MySQL database on another server?
If its a hosted database server and you have the secured endpoint URL (meaning https:// host) then just use that as the hostname host: 'hostname'
and that should be enough.
If it's a private server that you own and you have the SSL certificates then you can use the following:
const fs = require('fs');
const mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
port: '3306',
user: 'root',
password: 'passw0rd',
database: 'test',
ssl: {
ca: fs.readFileSync(__dirname + '/certs/ca.pem'),
key: fs.readFileSync(__dirname + '/certs/client-key.pem'),
cert: fs.readFileSync(__dirname + '/certs/client-cert.pem')
}
});
connection.connect();
You can connect using SSL using something like this:
const fs = require('fs');
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'hostname',
port : 'portnum',
user : 'db_user',
password : 'db_user_password',
database : 'db_name',
charset : 'utf8mb4',
ssl: {
ca: fs.readFileSync(__dirname + '/certs/ca.pem'),
key: fs.readFileSync(__dirname + '/certs/client-key.pem'),
cert: fs.readFileSync(__dirname + '/certs/client-cert.pem')
}
});
You must also enable SSL on the MySql server. There are some tutorials online showing how to, but you would need root access to do this.