@smarthivelabs-devs/auth-sdk
v1.5.0
Published
SmartHive Auth JavaScript/TypeScript SDK — core client for browser, Node.js, and React Native
Readme
@smarthivelabs-devs/auth-sdk
Core JavaScript/TypeScript SDK for SmartHive Auth. Framework-agnostic — works in the browser, Node.js 18+, and React Native. This is the foundation that auth-react, auth-expo, and auth-server are all built on.
Installation
npm install @smarthivelabs-devs/auth-sdk
# or
pnpm add @smarthivelabs-devs/auth-sdk
# or
yarn add @smarthivelabs-devs/auth-sdkPrerequisites
You need a SmartHive Auth project. From your SmartHive dashboard grab:
projectId— e.g.proj_abc123publishableKey— e.g.pk_live_abc123baseUrl— the URL of your SmartHive Auth service instance
Quick Start
import { initAuth } from "@smarthivelabs-devs/auth-sdk";
const client = initAuth({
projectId: "proj_abc123",
publishableKey: "pk_live_abc123",
baseUrl: "https://auth.myapp.com",
redirectUri: "https://myapp.com/auth/callback",
});
// Initialize (validates your project config against the server)
await client.initialize();
// Redirect the user to the SmartHive login page
await client.login();Configuration
interface SmartHiveAuthConfig {
/** Your SmartHive project ID */
projectId: string;
/** Your publishable (public) key */
publishableKey: string;
/** Base URL of your SmartHive Auth service */
baseUrl: string;
/**
* Custom branded auth domain (e.g. "https://auth.myapp.com").
* Used as the entry point for login/token flows.
* Falls back to baseUrl if not set.
*/
authDomain?: string;
/**
* Fallback auth domain if authDomain is unreachable.
* Useful for high-availability setups.
*/
fallbackAuthDomain?: string;
/** Default OAuth redirect URI after login */
redirectUri?: string;
/** Custom persistent storage adapter (default: localStorage in browser) */
storage?: AuthStorage;
/** Custom temporary storage for PKCE values (default: sessionStorage in browser) */
temporaryStorage?: AuthStorage;
/**
* URL of your own backend's social auth proxy (e.g. "https://api.myapp.com").
* When set, social OAuth initiations route through your domain so Google/Apple
* consent screens show your domain instead of SmartHive's.
* See auth-expo README → "Social Auth Proxy" for the full setup guide.
*/
socialProxyUrl?: string;
}API Reference
initAuth(config)
Creates and returns a SmartHiveAuthClient. Call this once at your app's entry point.
const client = initAuth({
projectId: "proj_abc123",
publishableKey: "pk_live_abc123",
baseUrl: "https://auth.myapp.com",
});client.initialize()
Validates your project configuration with the SmartHive server. Call this before any auth operations.
await client.initialize();Throws SmartHiveAuthError with code project_not_found if the project or key is invalid.
client.login(options?)
Starts the OAuth 2.0 + PKCE login flow by redirecting the user to the SmartHive login page.
// Basic login (uses redirectUri from config)
await client.login();
// Override the redirect URI for this login attempt
await client.login({ redirectUri: "https://myapp.com/auth/callback" });
// Pass custom state (returned in the callback URL)
await client.login({ state: "my-custom-state" });client.loginSocial(provider, options?)
Initiates a per-project social OAuth flow. The browser is redirected to the provider's consent screen using your project's own Google/Apple/GitHub credentials — the consent screen shows your app name, not SmartHive's.
// Redirect to Google's consent screen
await client.loginSocial("google");
// Override the redirect_uri that receives the tokens
await client.loginSocial("github", { redirectUri: "https://myapp.com/auth/social/callback" });Supported providers:
google · apple · github · facebook · twitter · linkedin · microsoft · discord · spotify · twitch · reddit · gitlab · slack · notion · zoom · figma
Configure each provider's credentials in your SmartHive dashboard under Project → OAuth Providers.
client.handleSocialCallback(options?)
Called on the page/route that your redirectUri points to after a social OAuth flow. Reads access_token and refresh_token from the URL query params, persists the session, and returns it.
// On your /auth/social/callback page — reads window.location automatically
const session = await client.handleSocialCallback();
// Or pass the URL explicitly (SSR / React Native)
const session = await client.handleSocialCallback({ url: window.location.href });
console.log(session.accessToken); // short-lived JWT
console.log(session.refreshToken); // long-lived session tokenThrows SmartHiveAuthError with code social_auth_failed if the provider returned an error, or callback_failed if no access_token is present.
client.handleCallback(options?)
Completes the OAuth flow on your callback route. Exchanges the authorization code for tokens and persists the session.
// In your /auth/callback page — reads from window.location automatically
const session = await client.handleCallback();
// Or pass the URL explicitly (useful in SSR or React Native)
const session = await client.handleCallback({ url: "https://myapp.com/auth/callback?code=...&state=..." });
console.log(session.accessToken);
console.log(session.refreshToken);
console.log(session.expiresAt); // Unix timestamp in msThrows SmartHiveAuthError with codes:
callback_failed— missing code or URLstate_mismatch— possible CSRF attackpkce_missing— PKCE verifier not found (session expired between steps)token_error— server rejected the code exchange
client.getSession()
Returns the current session from storage, or null if not signed in. Does not refresh expired tokens automatically.
const session = await client.getSession();
if (session) {
console.log("Signed in:", session.accessToken);
} else {
console.log("Not signed in");
}client.getAccessToken()
Returns a valid access token. Automatically refreshes using the refresh token if the access token is within 30 seconds of expiry.
const token = await client.getAccessToken();
if (token) {
// token is always fresh when truthy
}client.getAuthorizationHeader()
Returns a { authorization: "Bearer <token>" } header object ready to spread into fetch options. Returns an empty object if not signed in.
const headers = await client.getAuthorizationHeader();
const res = await fetch("/api/protected", { headers });client.fetch(input, init?)
Drop-in replacement for fetch that automatically injects the Authorization header.
// Identical to native fetch, but auth is handled automatically
const res = await client.fetch("/api/user/profile");
const res2 = await client.fetch("https://api.myapp.com/data", {
method: "POST",
body: JSON.stringify({ name: "Alice" }),
headers: { "content-type": "application/json" },
});client.refreshSession()
Explicitly refreshes the session using the stored refresh token. Returns the new session, or null if the refresh token is missing or expired (which also clears the stored session).
const newSession = await client.refreshSession();
if (!newSession) {
// Refresh token expired — user must log in again
await client.login();
}client.logout()
Clears the local session and calls the server-side sign-out endpoint.
await client.logout();
// User is now signed out — redirect them to your home/login pageclient.getUser()
Fetches the current user's profile from the SmartHive userinfo endpoint. Returns null if not signed in.
const user = await client.getUser();
console.log(user); // { sub: "user_123", email: "[email protected]", ... }client.verifyToken(token)
Verifies a raw access token against the SmartHive userinfo endpoint. Returns true if the token is valid and accepted by the server.
const isValid = await client.verifyToken(rawToken);client.headless.signUp.resendVerificationEmail(params)
Re-sends the email verification link to the given address. Use this when the user did not receive the initial email after signUp.email() returned requiresVerification: true.
await client.headless.signUp.resendVerificationEmail({ email: "[email protected]" });
// A fresh verification link is emailed — the previous link is still valid until it expiresThrows SmartHiveAuthError with code resend_failed on server error.
Custom Storage Adapter
By default the SDK uses localStorage for persistent storage and sessionStorage for PKCE state. Provide your own adapter to use any other storage backend (IndexedDB, AsyncStorage, SecureStore, Redis, etc.).
import { initAuth, type AuthStorage } from "@smarthivelabs-devs/auth-sdk";
const myStorage: AuthStorage = {
getItem: async (key) => {
return await myDatabase.get(key);
},
setItem: async (key, value) => {
await myDatabase.set(key, value);
},
removeItem: async (key) => {
await myDatabase.delete(key);
},
};
const client = initAuth({
projectId: "proj_abc123",
publishableKey: "pk_live_abc123",
baseUrl: "https://auth.myapp.com",
storage: myStorage,
});PKCE Helpers
Low-level PKCE utilities exported for advanced use cases (e.g. building your own auth client on top of this SDK).
import {
generateCodeVerifier,
generateCodeChallenge,
} from "@smarthivelabs-devs/auth-sdk";
const verifier = await generateCodeVerifier(); // random 32-byte base64url string
const challenge = await generateCodeChallenge(verifier); // SHA-256(verifier), base64url encodedUses the Web Crypto API — works in browsers and Node.js 18+.
Error Handling
All async methods throw SmartHiveAuthError on failure.
import { SmartHiveAuthError } from "@smarthivelabs-devs/auth-sdk";
try {
await client.login();
} catch (err) {
if (err instanceof SmartHiveAuthError) {
console.error(err.code); // e.g. "project_not_found"
console.error(err.message); // human-readable description
}
}Common error codes:
| Code | When |
|---|---|
| project_not_found | initialize() — invalid projectId or publishableKey |
| callback_failed | handleCallback() — no code in URL |
| state_mismatch | handleCallback() — OAuth state doesn't match (CSRF) |
| pkce_missing | handleCallback() — PKCE verifier not in storage |
| token_error | handleCallback() — server rejected code exchange |
Vanilla JS/TS Example (Full Flow)
import { initAuth, SmartHiveAuthError } from "@smarthivelabs-devs/auth-sdk";
const client = initAuth({
projectId: import.meta.env.VITE_AUTH_PROJECT_ID,
publishableKey: import.meta.env.VITE_AUTH_PUBLISHABLE_KEY,
baseUrl: import.meta.env.VITE_AUTH_BASE_URL,
redirectUri: `${window.location.origin}/auth/callback`,
});
// Entry point — runs on every page load
await client.initialize();
const session = await client.getSession();
// Login button
document.getElementById("login-btn")?.addEventListener("click", () => {
client.login();
});
// Logout button
document.getElementById("logout-btn")?.addEventListener("click", async () => {
await client.logout();
window.location.href = "/";
});
// Callback page (e.g. /auth/callback)
if (window.location.pathname === "/auth/callback") {
try {
await client.handleCallback();
window.location.href = "/dashboard";
} catch (err) {
if (err instanceof SmartHiveAuthError) {
console.error("Auth failed:", err.code, err.message);
}
}
}TypeScript Types
import type {
SmartHiveAuthConfig,
SmartHiveAuthClient,
AuthSession,
AuthStorage,
SocialProvider,
} from "@smarthivelabs-devs/auth-sdk";Related Packages
| Package | Use case |
|---|---|
| @smarthivelabs-devs/auth-react | React web apps — provider, hooks, components |
| @smarthivelabs-devs/auth-expo | React Native / Expo apps |
| @smarthivelabs-devs/auth-server | Express / Next.js server-side JWT verification |
License
MIT © SmartHive Labs
