Every Systron Node.js hosting plan includes MySQL database allocations. To store data securely, you need to create a database in Plesk and configure your Node.js code to establish a local connection.
Step 1: Create the Database in Plesk
- Log in to Plesk and click on Databases in the sidebar menu.
- Click Add Database.
- Enter a database name, create a database user, and set a strong password. Note these credentials down.
- Leave the database host as default (
localhostor127.0.0.1).
Step 2: Add Secure Environment Variables
Never hardcode database credentials directly into your application files. Instead, use Plesk's environment variable manager:
- Go to Websites & Domains > Node.js.
- Under the Environment Variables section, click Specify custom variables.
- Add the following key-value pairs:
DB_HOST=localhostDB_USER=[Your Database Username]DB_PASS=[Your Database Password]DB_NAME=[Your Database Name]
- Click OK to save.
Step 3: Code Implementation Snippet
Ensure you have installed the mysql2 package via npm or Yarn. You can then use the following connection structure in your entry file (e.g., app.js or server.js) to read the Plesk environment variables securely:
const mysql = require('mysql2');
// Create the connection connection configuration
const connection = mysql.createConnection({
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
// Test the connection
connection.connect((err) => {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Successfully connected to the Systron MySQL database.');
});
Once your script is updated, click Restart App on your Plesk Node.js dashboard to initialize the database connection.