SDK JavaScript
@authon/js — SDK universal de navegador que funciona em qualquer ambiente JavaScript. Renderiza um modal de login drop-in via ShadowDOM com personalização completa de aparência.
Instalação
npm install @authon/jsOu carregue de um CDN para prototipação rápida:
<script type="module">
import { Authon } from "https://cdn.jsdelivr.net/npm/@authon/js/+esm";
</script>Inicialização
Crie uma instância Authon com sua chave publicável. Encontre sua chave no Dashboard em Chaves de 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 Modal de Login
Chame openSignIn() ou openSignUp() para exibir o modal do Authon. O modal é renderizado em uma raiz ShadowDOM para nunca conflitar com os estilos do seu app.
// Open the sign-in modal
await authon.openSignIn();
// Open the sign-up modal (registration flow)
await authon.openSignUp();Ambos os métodos são assíncronos — eles buscam o branding do seu projeto e a lista de provedores OAuth da API antes de renderizar, para que o modal sempre reflita as configurações do seu dashboard.
Autenticação por E-mail
Para fluxos totalmente programáticos (ex.: sua própria UI personalizada), chame os métodos de e-mail diretamente:
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" },
);Login com OAuth
Acione um popup OAuth para qualquer provedor configurado no seu dashboard. O popup gerenciará o fluxo PKCE e enviará uma mensagem de volta para sua janela ao concluir.
// Supported providers: google | apple | github | kakao | naver |
// facebook | discord | x | line | microsoft
await authon.signInWithOAuth("google");
await authon.signInWithOAuth("github");
await authon.signInWithOAuth("kakao");Usuário e Sessão
// 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
Inscreva-se em eventos do ciclo de vida de autenticação com authon.on(event, callback). O método retorna uma função de cancelamento de inscrição.
// 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();Personalização de Aparência
Substitua o branding programaticamente via configuração appearance . Essas configurações se mesclam com o branding definido no Dashboard.
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",
},
});Limpeza
Chamedestroy() para remover ouvintes de eventos, fechar o modal e limpar os dados de sessão quando seu app for desmontado.
// In a SPA — call on route change or component unmount
authon.destroy();Exemplo 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";
}