NodeJS connection to MySQL 8.0 fails with authentication protocol error

I’m having trouble connecting to my MySQL 8.0 database from a Node.js app. I’ve set up the latest MySQL Community 8.0 and Node.js with default settings, but I keep getting an error.

Here’s my Node.js code:

const db = require('mysql');

const connection = db.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'mypassword',
  insecureAuth: true
});

connection.connect((error) => {
  if (error) {
    console.error('Connection failed:', error);
  } else {
    console.log('Connected successfully!');
  }
});

When I run this, I get an error saying the client doesn’t support the authentication protocol. It suggests upgrading the MySQL client, but I’m already using the latest version.

I’ve looked at some docs and GitHub issues, but I’m still stumped. Any ideas on how to fix this? Is there something I’m missing in my setup or code?

hey laura, ive had this issue before. its a pain! try changing the authentication method for ur mysql user. run this SQL command:

ALTER USER ‘root’@‘localhost’ IDENTIFIED WITH mysql_native_password BY ‘mypassword’;

Then flush privileges. should fix it!

Connecting to MySQL 8.0 can be challenging due to changes in the authentication protocol. In my experience, switching to a more up-to-date driver helped resolve the issue. I encountered a similar problem and solved it by moving from the mysql package to mysql2. After installing mysql2 via npm, I updated the code to require mysql2 instead. For instance:

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'mypassword'
});

This solution addressed the protocol error without modifying the database configuration, and it has worked reliably in my projects.