SDK de JavaScript
@authon/js — SDK universal para navegador que funciona en cualquier entorno JavaScript. Renderiza un modal de inicio de sesión integrado mediante ShadowDOM con personalización completa de apariencia.
Instalación
npm install @authon/jsO carga desde una CDN para prototipos rápidos:
<script type="module">
import { Authon } from "https://cdn.jsdelivr.net/npm/@authon/js/+esm";
</script>Inicialización
Crea una instancia de Authon con tu clave publicable. Encuentra tu clave en el Panel bajo Claves API.
import { Authon } from "@authon/js";
const authon = new Authon("pk_live_your_publishable_key", {
// Optional — override the API base URL (default: https://api.authon.dev)
apiUrl: "https:1
2
mode: "popup",
3
theme: "auto",
4
locale: "en",
});Abrir el modal de inicio de sesión
Llama a openSignIn() o openSignUp() para mostrar el modal de Authon. El modal se renderiza en una raíz ShadowDOM para que nunca interfiera con los estilos de tu app.
// Open the sign-in modal
await authon.openSignIn();
// Open the sign-up modal (registration flow)
await authon.openSignUp();Ambos métodos son asíncronos — obtienen la identidad de marca de tu proyecto y la lista de proveedores OAuth de la API antes de renderizar, por lo que el modal siempre refleja la configuración de tu panel.
Autenticación por correo
Para flujos completamente programáticos (ej. tu propia UI personalizada), llama a los métodos de correo directamente:
import type { AuthonUser } from "@authon/js";
// Sign in an existing user
const user: AuthonUser = await authon.signInWithEmail(
"user@example.com",
"securepassword",
);
// Register a new user
const user: AuthonUser = await authon.signUpWithEmail(
"newuser@example.com",
"securepassword",
{ displayName: "Jane Doe" },
);Inicio de sesión con OAuth
Activa una ventana emergente OAuth para cualquier proveedor configurado en tu panel. La ventana emergente gestionará el flujo PKCE y enviará un mensaje de vuelta a tu ventana al completarse.
// Supported providers: google | apple | github | kakao | naver |
// facebook | discord | x | line | microsoft
await authon.signInWithOAuth("google");
await authon.signInWithOAuth("github");
await authon.signInWithOAuth("kakao");Usuario y sesión
// Get the current signed-in user (returns null if not signed in)
const user = authon.getUser();
// {
// id: "usr_abc123",
// email: "user@example.com",
// displayName: "Jane Doe",
// avatarUrl: "https://...",
// emailVerified: true,
// isBanned: false,
// publicMetadata: {},
// createdAt: "2026-01-01T00:00:00Z",
// }
// Get the raw JWT access token for API calls
const token = authon.getToken();
// Sign out the current user and clear local session
await authon.signOut();Eventos
Suscríbete a eventos del ciclo de vida de autenticación con authon.on(event, callback). El método retorna una función para cancelar la suscripción.
// Fired when a user successfully signs in or the session is restored
const unsubSignedIn = authon.on("signedIn", (user) => {
console.log("Signed in:", user.email);
router.push("/dashboard");
});
// Fired when the user signs out or the session expires
const unsubSignedOut = authon.on("signedOut", () => {
console.log("Signed out");
router.push("/");
});
// Fired when a token is auto-refreshed
authon.on("tokenRefreshed", (token) => {
console.log("Token refreshed:", token.slice(0, 16) + "...");
});
// Fired on any API or auth error
authon.on("error", (error) => {
console.error("Auth error:", error.message);
});
// Unsubscribe when needed
unsubSignedIn();
unsubSignedOut();Personalización de apariencia
Sobreescribe la identidad de marca de forma programática mediante la configuración appearance . Estos ajustes se fusionan con la identidad de marca que configures en el Panel.
const authon = new Authon("pk_live_your_key", {
appearance: {
brandName: "Acme Corp",
primaryColorStart: "#7c3aed",
primaryColorEnd: "#4f46e5",
darkBg: "#0f172a",
darkText: "#f1f5f9",
borderRadius: 12,
showEmailPassword: true,
showDivider: true,
termsUrl: "https:0
privacyUrl: "https://acme.com/privacy",
},
});Limpieza
Llama adestroy() para eliminar los listeners de eventos, cerrar el modal y limpiar los datos de sesión cuando tu app se desmonte.
// In a SPA — call on route change or component unmount
authon.destroy();Ejemplo completo
import { Authon } from "@authon/js";
const authon = new Authon("pk_live_your_key", {
mode: "popup",
theme: "dark",
appearance: {
brandName: "My App",
primaryColorStart: "#7c3aed",
primaryColorEnd: "#4f46e5",
},
});
// Event listeners
authon.on("signedIn", (user) => {
userNameEl.textContent = user.displayName ?? user.email ?? "";
authSection.style.display = "block";
loginBtn.style.display = "none";
});
authon.on("signedOut", () => {
authSection.style.display = "none";
loginBtn.style.display = "block";
});
authon.on("error", (err) => {
console.error("Authon error:", err.message);
});
// Wire up buttons
loginBtn.addEventListener("click", () => authon.openSignIn());
logoutBtn.addEventListener("click", () => authon.signOut());
// Check if user is already signed in on page load
const user = authon.getUser();
if (user) {
userNameEl.textContent = user.displayName ?? user.email ?? "";
authSection.style.display = "block";
loginBtn.style.display = "none";
}