Can’t connect to EC2 Ubuntu instance from Next.js (JavaScript) via SSH

I’m trying to establish an SSH connection from my Next.js application to an AWS EC2 instance, but I’m encountering authentication failures. Here’s my setup:

  • Next.js application (JavaScript)
  • AWS EC2 instance running Ubuntu
  • Using ssh2-no-cpu-features library for SSH connection
import { Client } from 'ssh2-no-cpu-features';

const EC2_CONFIG = {
    host: 'XXXXXX.eu-north-1.compute.amazonaws.com',
    port: 22,
    username: 'ubuntu',
    algorithms: {
        kex: [
            'ecdh-sha2-nistp256',
            'ecdh-sha2-nistp384',
            'ecdh-sha2-nistp521'
        ],
        cipher: [
            'aes128-ctr',
            'aes192-ctr',
            'aes256-ctr',
            'aes128-gcm',
            'aes256-gcm'
        ],
        serverHostKey: [
            'ssh-rsa',
            'ecdsa-sha2-nistp256',
            'ssh-ed25519'
        ],
        hmac: [
            'hmac-sha2-256',
            'hmac-sha2-512'
        ]
    },
    debug: process.env.NODE_ENV === 'development' ? console.log : undefined,
    readyTimeout: 30000
};

function formatPrivateKey(key) {
    if (!key) throw new Error("Private key not found in environment variables");

    return key
        .trim()
        .replace(/\n/g, 'n'); // Handle escaped newlines
}

async function createSSHConnection() {
    const conn = new Client();

    try {
        const privateKey = formatPrivateKey(process.env.AWS_PRIVATE_RSA);
        const config = { ...EC2_CONFIG, privateKey };

        return new Promise((resolve, reject) => {
            conn.on('ready', () => {
                console.log('Connection ready');
                resolve(conn);
            });
            conn.on('error', (err) => {
                console.error('Connection error:', err);
                reject(err);
            });
            conn.connect(config);
        });
    } catch (error) {
        throw new Error(`SSH Connection failed: ${error.message}`);
    }
}

AWS_PRIVATE_RSA="-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxGXAftWaE8kRSAWHRmKA/Jx9VtCyd2A3lal708ZnowfWCEyh
................
-----END RSA PRIVATE KEY-----"

I aim to connect to EC2, execute a command, and receive an answer to proceed.

The error:
Inbound: Received USERAUTH_FAILURE (publickey) Client: publickey (rsa-sha2-256) auth failed Client: publickey auth failed Connection error: Error: All configured authentication methods failed