alexa-connector
v0.9.0
Published
A Node.js client for interacting with the Amazon Alexa web API, inspired by alexa_media_player integration for Home Assistant.
Maintainers
Readme
Alexa-Connector
A robust, extensible Node.js client for interacting with the unofficial Amazon Alexa Web API. Inpsired by the Alexa Media Player HACS integration for Home Assistant.
This library bypasses the restrictive official Alexa Skills Kit by mimicking a web browser session. It handles the complex authentication state machine, CSRF token extraction, and cookie management required to send commands (like Text-to-Speech or routine triggers) directly to your Alexa devices.
It natively supports both CommonJS and ES Modules and features built-in, automated session persistence.
✨ Features
- Universal Compatibility: Works out of the box with
require()(CommonJS) andimport(ES Modules). - Automated Cookie Persistence: Simply provide a file path, and the library will seamlessly save and load your authentication session to avoid logging in on every request.
- Extensible Hooks: Run custom asynchronous logic immediately before authentication, after successful authentication, or upon failure.
- Event-Driven: Extends the native Node.js
EventEmitter, allowing your application to listen for state changes without cluttering your configuration.
📦 Installation
npm install alexa-connector
🚀 Quick Start
Because the library handles file system operations internally via the authFilePath option, your implementation stays incredibly clean.
ES Modules (import)
import AlexaClient from 'alexa-connector';
import path from 'path';
// ... (use the same setup as below)
CommonJS (require)
const AlexaClient = require('alexa-connector');
const path = require('path');
async function start() {
// 1. Initialize the client
const alexa = new AlexaClient({
email: '[email protected]',
password: 'your_password',
amazonDomain: 'amazon.com', // e.g., amazon.co.uk, amazon.de
// Supplying this path tells the library to auto-save and auto-load your session!
authFilePath: path.join(__dirname, 'alexa-cookie-session.json'),
// --- OPTIONAL LIFECYCLE HOOKS ---
onBeforeAuth: async () => {
console.log("-> [Hook] Preparing authentication flow...");
}
});
// --- EVENT LISTENERS ---
alexa.on('sessionLoaded', (file) => console.log(`-> [Event] Restored session from ${file}`));
alexa.on('sessionSaved', (file) => console.log(`-> [Event] Saved new session to ${file}`));
alexa.on('authSuccess', () => console.log("-> [Event] Authentication successful!"));
alexa.on('authFail', (error) => console.error(`-> [Event] Auth failed: ${error.message}`));
// 2. Execute Authentication
try {
await alexa.authenticate();
// 3. Send a Command
console.log("Sending command to Alexa...");
const response = await alexa.sendSequenceCommand('YOUR_DEVICE_SERIAL', 'DEVICE_TYPE', {
type: 'Alexa.Speak',
payload: {
textToSpeak: 'Hello from Node.js!'
}
});
console.log("Success!", response);
} catch (error) {
console.error("Fatal Error:", error);
}
}
start();
⚙️ API Reference
new AlexaClient(config)
| Property | Type | Required | Description |
| --- | --- | --- | --- |
| email | string | Yes | Your Amazon account email. |
| password | string | Yes | Your Amazon account password. |
| amazonDomain | string | No | Your regional Amazon domain (default: amazon.com). |
| authFilePath | string | No | Absolute path to a JSON file. If provided, the library will auto-save/load cookies here. |
| onBeforeAuth | Function | No | Sync/Async function to run before the auth flow begins. |
| onAfterAuth | Function | No | Sync/Async function to run after a successful login. Passes the CookieJar. |
| onAuthFail | Function | No | Sync/Async function to run if login fails. Passes the Error. |
Events
sessionLoaded(filePath): Emitted when valid cookies are successfully read fromauthFilePath.sessionSaved(filePath): Emitted when fresh cookies are successfully written toauthFilePath.authStart: Emitted when theauthenticate()method begins executing.authSuccess(cookieJar): Emitted upon successful login and CSRF extraction.authFail(error): Emitted if the login flow is interrupted (e.g., bad password, unhandled CAPTCHA).
⚠️ Disclaimer
This library uses the unofficial Alexa Web API. Amazon can change their authentication flow or web endpoints at any time, which may break this library. Due to Amazon's bot-detection, you may encounter CAPTCHAs or 2FA (One-Time Password) prompts.
📄 License
MIT
