SDK Quickstart

This guide will help you integrate Block-Auth authentication into any React, Vue, or Angular application as simply and seamlessly as possible.

The SDK is built as a headless core + thin per-framework bindings: all the logic (WebSocket protocol, wallets, OAuth, session state) lives in @block-auth.io/core, and each framework consumes it through its own binding — @block-auth.io/react, @block-auth.io/vue, or @block-auth.io/angular — all exposing the same UI surface. Every code example below has a tab per framework.


1. Installation

To install the SDK, add the framework-agnostic core alongside your framework binding:

# Using NPM
npm install @block-auth.io/core @block-auth.io/react

# Using Yarn
yarn add @block-auth.io/core @block-auth.io/react

Styles are injected automatically — when you import the binding (React/Vue) or register provideBlockAuth (Angular). There is no separate CSS file to import. (Internally the bindings depend on @block-auth.io/ui-styles, but you do not need to install or import it yourself.)

Peer dependencies (provided by your app):

  • React: react and react-dom >=16.8.0 (hooks)
  • Vue: vue >=3.4.0
  • Angular: @angular/core and @angular/common >=20.0.0

2. Importing Components

Everything you need is exported from your framework binding, and styles are injected automatically — you no longer need to import a CSS file manually.

Block-Auth provides many components and hooks, but for a standard integration you only need three pieces:

  • A provider — creates the client from your config and makes it available to the whole app: BlockAuthProvider (React), the createBlockAuth plugin (Vue), or provideBlockAuth (Angular).
  • FlowBlockAuth — the login orchestrator (sign-in / sign-up modals + status button, and the profile dropdown once connected). In Angular it is the <ba-flow-block-auth> standalone component.
  • DropdownProfile — the profile/session dropdown, when you want to place it on its own (e.g., a navbar).

Add the imports to the file where you will integrate the login:

// Import the components you need from the React binding
import { BlockAuthProvider, FlowBlockAuth, DropdownProfile } from "@block-auth.io/react";

3. Implementing the Main Component

Integration has three parts, and only the syntax changes per framework:

  1. A config object with your credentials and provider settings — identical across frameworks (type BlockAuthClientConfig, exported from @block-auth.io/core).
  2. A provider that creates the client from config and makes it available to every Block-Auth component and hook. Your credentials live here — not on the individual components.
  3. FlowBlockAuth renders the login interface and, once connected, initializes the SDK runtime and shows the profile dropdown automatically.

3.1 The config object

Configure the variables obtained from your Dashboard. All keys are camelCase and live in a single flat object (e.g., in a dedicated config/blockauth.js). Because this config is consumed by the provider in the browser, it carries only the publishable apiKey — no secret:

export const config = {
  apiKey: "YOUR_API_KEY", // publishable key — e.g., "app.65b0ee79..."; public by design
  locale: "en",           // "en" | "es"
  // NOTE: do NOT add apiSecret here. This object runs in the browser;
  // the SDK ignores apiSecret in the browser and it would leak into your bundle.
  google: {
    clientId: "YOUR_GOOGLE_CLIENT_ID",
  },
  microsoft: {
    clientId: "YOUR_MICROSOFT_CLIENT_ID",
    tenantId: "common",
    authorityMode: "common",
  },
};

A minimal browser config is just the publishable key:

<BlockAuthProvider config={{ apiKey: 'app.65b0...' /* publishable key */ }}>
  <FlowBlockAuth />
</BlockAuthProvider>

3.2 Provide the client

Register the provider once, at the root of your app:

// App.jsx — wrap your tree with the provider
import { BlockAuthProvider } from "@block-auth.io/react";
import { config } from "./config/blockauth";
import Login from "./pages/Login";

export default function App() {
  return (
    <BlockAuthProvider config={config}>
      <Login />
    </BlockAuthProvider>
  );
}

3.3 Render the login flow

Here is a complete example of what your authentication view should look like:

import { useState } from "react";
import { FlowBlockAuth } from "@block-auth.io/react";

export default function Login() {
  const [isLogged, setIsLogged] = useState(false);

  // Callback to define custom logic when registration or login is successful.
  // It receives the authenticated user's address / DID.
  const handleSuccess = async (address) => {
    console.log("Success! Authorized for address:", address);
    setIsLogged(true);
  };

  // Callback for errors
  const handleError = async () => {
    console.error("An error occurred during authentication.");
  };

  return (
    <div className="app-container">
      {isLogged && <h2>Session started successfully!</h2>}
      <FlowBlockAuth
        onSuccess={handleSuccess}
        onError={handleError}
        onLogout={() => setIsLogged(false)}
      />
    </div>
  );
}

3.4 Server-side admin operations (Node)

The browser SDK above never needs apiSecret. Administrative operations — reading your app model, verifying a signed address, and other privileged calls — run on your own server with the blockauth-sdk provider, which does take apiSecret.

This is the only place apiSecret belongs. It is a server-only credential: it lives in a server environment variable, never in frontend code, and never reaches the browser.

// server.js — runs on YOUR Node backend, never bundled into the frontend
import { BlockAuthProvider } from "blockauth-sdk";

const provider = new BlockAuthProvider({
  apiKey: process.env.BLOCKAUTH_API_KEY,       // publishable key
  apiSecret: process.env.BLOCKAUTH_API_SECRET, // server-only secret — keep off the frontend
});

// Connect the backend to the Block-Auth provider (blockchain + API), then authenticate.
await provider.connect();
await provider.signin();

// Privileged, admin-level operations run here on the server:
const app = await provider.app();                 // your app model (roles, permissions, …)
const result = await provider.isAddressSigned(userAddress); // verify a user's signed address

See Authentication with the Block-Auth SDK for full backend examples (Express, JWT bridge, etc.).

Understanding the code

  • 1) Configuration

    • Config Object (config): A single flat object (camelCase keys) with your publishable apiKey, UI language (locale), and optional provider/transport settings (google, microsoft, wsUrl, walletConnectProjectId). In the browser it carries only the publishable apiKey — apiSecret is a server-only credential and is ignored if passed here (see section 3.4).
    • Provider: Creates the client from config once and provides it to every Block-Auth component and hook — BlockAuthProvider (React), createBlockAuth plugin (Vue), provideBlockAuth (Angular). This is where credentials and provider setup go — the components themselves no longer take apiKey/apiSecret.
    • Provider Scope: In React you can wrap the full app or only the sections that use Block-Auth components/hooks; in Vue and Angular the provider is registered app-wide (main.ts / app.config.ts). Full-app scope is usually simpler for teams.
  • 2) Authentication and Session Flow

    • Success Callback: Triggered automatically by FlowBlockAuth after successful authentication, providing the user address/DID — onSuccess prop (React), :on-success prop (Vue), (success) output (Angular).
    • Self-managed UI: FlowBlockAuth shows the sign-in/sign-up flow when there is no session and, once connected, initializes the SDK runtime and swaps to the profile dropdown automatically (controlled by showDropdownWhenConnected, true by default). Your own isLogged state is only needed for your app's UI, not for the Block-Auth widget.
  • 3) Credentials and Ownership

    • config.apiKey (the publishable key) and apiSecret are obtained during Link your application in Integration Quickstart. Only apiKey goes in the browser; apiSecret stays on the server (see section 3.4).
    • config.google.clientId, config.microsoft.clientId, and config.microsoft.tenantId are managed by the BlockAuth team during the integration process.
    • The publishable apiKey is safe to ship in your frontend; there is no secret to protect here. apiSecret is used only by your backend, where it must be kept in secure server-side storage.

Placing DropdownProfile on its own

If you prefer to render the profile/session dropdown somewhere else (e.g., a navbar on an already-authenticated page) instead of letting FlowBlockAuth show it, use DropdownProfile — but it does not start the connection by itself. Start the SDK runtime once inside the same provider to establish the session, then render DropdownProfile. Each framework exposes the runtime idiomatically: a component (React), a composable (Vue), or a directive (Angular):

import { BlockAuthRuntime, DropdownProfile } from "@block-auth.io/react";

// Inside <BlockAuthProvider config={config}>
function AccountMenu() {
  return (
    <>
      {/* Starts connect → restore session → wires SDK events */}
      <BlockAuthRuntime onLogout={() => console.log("logged out")} />
      <DropdownProfile onLogout={() => console.log("logged out")} />
    </>
  );
}

Reading the session (roles, user profile)

Inside the provider you can read the authenticated user — useBlockAuthUser (React hook / Vue composable) or the BlockAuthService signals (Angular) — with helpers such as roleNames, hasRole(slug), and isLoadingUser:

import { useBlockAuthUser } from "@block-auth.io/react";

function RolesPanel() {
  const { roleNames, hasRole, isLoadingUser } = useBlockAuthUser();
  if (isLoadingUser) return <p>Loading roles…</p>;
  return <p>Your roles: {roleNames.join(", ") || "none"}</p>;
}

4. Integrate with Your Existing Login System

Block-Auth is usually integrated as an additional authentication method. Most production apps need a bridge between the SDK callback and their own session model.

Recommended generic flow

  1. User authenticates with FlowBlockAuth.
  2. onSuccess returns the user identifier (address / DID).
  3. Frontend calls your backend login bridge endpoint.
  4. Backend maps or verifies the identity and returns your app session.
  5. Frontend stores your app session and continues the normal logged-in flow.

Minimal frontend contract

Your frontend should expect a backend response with at least:

{
  "token": "YOUR_APP_JWT_OR_SESSION_TOKEN",
  "role": "user",
  "full_name": "Jane Doe"
}

Coexistence with existing auth methods

Block-Auth can be your primary authentication experience, including in production-grade architectures. If your application already has password, OTP, or SSO flows, you can integrate Block-Auth as an additional sign-in option during migration or hybrid rollout phases.


5. Production Connectivity and CSP Setup

This section is intentionally framework-agnostic for frontend architecture and applies to any app — React, Vue, or Angular, whatever the toolchain (Vite, CRA, Next.js, Nuxt, Angular CLI, etc.). If Block-Auth runs in the browser, your frontend host must allow the SDK network targets through CSP.

Why this is necessary

  • Browser-enforced CSP: Even with correct frontend code, the browser blocks requests to non-allowed domains.
  • SDK transport requirements: Block-Auth needs outbound API and WebSocket connectivity.
  • Deployment consistency: Explicit CSP rules reduce environment-only failures in staging and production.

Universal implementation

Use the same integration shown in section 3. Implementing the Main Component, and set wsUrl in your config object (passed to BlockAuthProvider) according to your deployment endpoint. If omitted, it defaults to the production endpoint wss://wss.block-auth.io.

Apply this CSP configuration on the server/gateway that returns your frontend (Express, Nginx, or equivalent):

  • Express apps: add it in your server bootstrap file (commonly server.js, app.js, or backend/index.js) in the middleware section, before serving frontend assets/routes.
  • Nginx deployments: define the equivalent CSP header in your site/server config (nginx.conf or virtual host file) for the frontend responses.
const cspConnectSrc = [
  "'self'",
  "https://api.block-auth.io",
  "wss://wss.block-auth.io",
  "wss://your-ws-endpoint.example.com",
  "https://accounts.google.com",
  "https://login.microsoftonline.com",
  "https://graph.microsoft.com",
  "https://*.msauth.net",
];

const cspScriptSrc = [
  "'self'",
  "'unsafe-inline'",
  "https://accounts.google.com",
  "https://apis.google.com",
  "https://www.gstatic.com",
  "https://*.gstatic.com",
  "https://login.microsoftonline.com",
];

const cspImgSrc = [
  "'self'",
  "data:",
  "blob:",
  "https:",
];

const cspFrameSrc = [
  "'self'",
  "https://accounts.google.com",
  "https://login.microsoftonline.com",
  "https://*.microsoftonline.com",
  "https://*.block-auth.io",
];

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        connectSrc: cspConnectSrc,
        scriptSrc: cspScriptSrc,
        imgSrc: cspImgSrc,
        frameSrc: cspFrameSrc,
      },
    },
  })
);

Note: It does not matter whether your CSP is configured in Express, Nginx, or another gateway. What matters is the final CSP header received by the browser.


6. Security Checklist

Use this checklist before going live:

  • Never put apiSecret in the frontend — not hardcoded, and not in bundler environment variables (VITE_…, NEXT_PUBLIC_…, REACT_APP_…). Those are not secret: the bundler inlines them into the JavaScript bundle shipped to the browser, where anyone can read them. It is false security. The apiSecret belongs only on your server; the SDK also strips it if passed in the browser. The publishable apiKey is public by design and safe to ship in the frontend.
  • Keep apiSecret in server-side environment variables (or a secrets manager) on your backend only, and rotate credentials regularly.
  • Validate and sanitize the identity value (address / DID) before creating local sessions.
  • Protect your backend bridge endpoint with rate limiting and logging.
  • Store session tokens securely and follow your platform session hardening practices.

7. Customization Options (Props)

Credentials and provider settings are configured on the provider via config (see section 3). The components below take only behavior, callback, and styling props. The lists reflect the current SDK behavior.

Props are documented with their React names; the same surface exists in every binding with the framework's idiom:

  • Vue: same props in kebab-case (:on-success, :dropdown-btn-size, :show-dropdown-when-connected, …).
  • Angular: styling/behavior props are inputs ([dropdownBtnSize], [showDropdownWhenConnected], …) and lifecycle callbacks are outputs — (success), (errored), (loggedOut) — except DropdownProfile's [onLogout], which is an awaitable function input.

config (passed to the provider: BlockAuthProvider / createBlockAuth / provideBlockAuth)

  • apiKey (string, required): Publishable key — public by design and safe to ship in the browser (like Stripe's pk_).
  • apiSecret (string, server-only): Secret credential for backend administrative use only. Do not pass it in the browser — the SDK ignores (strips) it there. Optional/unused for the browser provider; required only for the server-side blockauth-sdk provider (see section 3.4).
  • locale (string): UI language — "en" or "es".
  • wsUrl (string): WebSocket endpoint (default: wss://wss.block-auth.io).
  • walletConnectProjectId (string): Enables WalletConnect via QR when provided.
  • rpcUrl (string): Custom RPC URL for EVM wallets.
  • wsConnectTimeout (number) / wsConnectRetries (number): Tuning for the initial WS connect (defaults: 300 ms, 3).
  • google (object): { clientId, scope? }.
  • microsoft (object): { clientId, tenantId, authorityMode?, redirectUri? } (authorityMode: "common" | "tenant").

FlowBlockAuth — Callbacks

  • onSuccess (function): Asynchronous callback executed after a successful login; receives the user address / DID.
  • onError (function): Asynchronous callback executed when an error occurs.
  • onLogout (function): Asynchronous callback executed when logging out.

FlowBlockAuth — Behavior and Interface

  • showDropdownWhenConnected (boolean): Shows the profile dropdown when an active session is detected (default: true).
  • initializeSdk (boolean): Whether this component starts the SDK runtime/connection (default: true). Set to false if another component (e.g., BlockAuthRuntime) already owns the runtime.
  • isInsideModal (boolean): Set to true when rendering inside a custom modal container (default: false).
  • containerRef (ref): Container reference used with isInsideModal for click-outside behavior.
  • buttonText (string): Custom label for the status button.

FlowBlockAuth — Styling

  • btnClassNames
  • btnTextClassNames
  • dropdownBtnSize (string): "xs", "small", "base", or "large" (default: "small").
  • dropdownBtnBgClassNames
  • dropdownBtnTextColorClassNames
  • dropdownBtnBorderClassNames
  • dropdownHeight (number)
  • additionalDropdownItems (array): Add extra options to the user's dropdown menu — each item: { onClick, text, firstIcon?, disabled? }, where text is a string or a locale map ({ es, en }).

DropdownProfile

Use standalone (with the SDK runtime, see below) to render the profile/session dropdown on its own.

  • onLogout (function): Asynchronous callback executed when logging out.
  • onNavigate (function): Host-app navigation for the "My profile" item.
  • isInsideModal (boolean) / containerRef (ref): Same modal/click-outside behavior as above.
  • dropdownBtnSize, dropdownBtnBgClassNames, dropdownBtnTextColorClassNames, dropdownBtnBorderClassNames, dropdownHeight, additionalDropdownItems: Same styling props as FlowBlockAuth.

The SDK runtime

Headless piece that starts the connection and wires SDK events; start it once (inside the provider) when you use DropdownProfile on its own. Idiomatic per framework:

  • React: <BlockAuthRuntime /> component.
  • Vue: useBlockAuthRuntime(useClient(), callbacks) composable.
  • Angular: [baRuntime] directive (e.g., on an <ng-container>).

It exposes the same lifecycle callbacks as FlowBlockAuth: onSuccess, onError, onLogout (Angular: (success), (errored), (loggedOut) outputs).

Localization

  • Language is controlled through the provider's config.locale, not through a component language prop.
  • Available values are currently es and en.

Was this page helpful?