---
title: "React, Vue or Angular: link users and more"
description: "Link the users you already have, show your UI based on their roles and read your app data from your server."
url: "/sdk-integration-spa-extras/"
language: "en"
guide: "React, Vue, Angular (+ backend)"
step: "More options, optional"
---

# Link users and more

Optional. For apps that already have their own users, that change their UI based on roles, or that read Block-Auth data from the server.

## Link existing users (optional)

If your app already has its own users, they can link their Block-Auth identity to their account. After that, signing in with Block-Auth returns their id in your app as `externalId`, so you can sign them in as **your** user.

**In your frontend,** show `LinkBlockAuth` to a user who is signed in with your own login:

**React · The user’s account page · e.g. src/pages/AccountPage.jsx**

```jsx
import { LinkBlockAuth } from '@block-auth.io/react'

const messages = {
  already_linked: 'This Block-Auth account is already linked to another user.',
  not_signed_in: 'Sign in again to link your account.',
  failed: 'Linking failed, try again.',
}

export function LinkAccount() {
  return (
    <LinkBlockAuth
      onLinked={() => window.location.reload()}
      onError={(reason) => alert(messages[reason])}
    />
  )
}
```

**Vue · The user’s account page · e.g. src/views/AccountView\.vue**

```vue
<template>
  <LinkBlockAuth :on-linked="onLinked" :on-error="onError" />
</template>

<script setup>
import { LinkBlockAuth } from '@block-auth.io/vue'

const messages = {
  already_linked: 'This Block-Auth account is already linked to another user.',
  not_signed_in: 'Sign in again to link your account.',
  failed: 'Linking failed, try again.',
}

const onLinked = () => window.location.reload()
const onError = (reason) => alert(messages[reason])
</script>
```

**Angular · The user’s account page · e.g. src/app/link-account.component.ts**

```typescript
import { Component } from '@angular/core'
import { LinkBlockAuthComponent } from '@block-auth.io/angular'

@Component({
  selector: 'app-link-account',
  imports: [LinkBlockAuthComponent],
  template: `<ba-link-block-auth (linked)="onLinked()" (errored)="onError($event)" />`,
})
export class LinkAccountComponent {
  private readonly messages: Record<string, string> = {
    already_linked: 'This Block-Auth account is already linked to another user.',
    not_signed_in: 'Sign in again to link your account.',
    failed: 'Linking failed, try again.',
  }

  onLinked(): void {
    window.location.reload()
  }

  onError(reason: string): void {
    alert(this.messages[reason])
  }
}
```

**Only for Angular:**

**Angular with `templateUrl`:** the examples put the HTML inside `template`. If your component has its HTML in its own file (`templateUrl`, the default in new Angular projects, like `app.ts` and `app.html`), move what's inside `template` to that `.html` file and keep the rest (`imports` and the methods) in the `.ts` file.

The button opens the login in a popup. If the browser blocks it, it opens in the same tab: Block-Auth sends the user back to the root of your app (`/`) and `LinkBlockAuth` finishes the link on the page where it started.

> How you add the backend login routes: this page covers “With the Block-Auth package” or “My own implementation”. Both variants are written out below, each one marked. Follow only the one that matches the app.

### How you add the backend login routes: With the Block-Auth package.

**In your backend,** tell the [Block-Auth package](/sdk-integration-spa-backend.md#backend-routes) who is signed in with your own login (`appUser`) and save the link (`onLinked`). With `appUser`, the package turns on `GET /link` (is this user linked?) and `POST /link` (links them, or answers `409` if the identity or your user is already linked):

**Node.js · server.js · where you create your Express app**

```javascript
export const routes = new BlockAuthRoutes({
  apiKey: BLOCKAUTH_API_KEY,
  apiSecret: BLOCKAUTH_API_SECRET,
  appUrl: APP_URL,
  appUser: async ({ session }) => {
    const id = session.get('userId')
    return id ? { id, linked: await isLinked(id) } : null
  },
  onLinked: (id, user) => saveLink(id, user.address),
})
```

**PHP · public/index.php · your entry point**

```php
$routes = new BlockAuthRoutes(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'), [
    'appUrl' => getenv('APP_URL'),
    'appUser' => function ($session): ?array {
        $id = $session->get('user_id');
        return $id === null ? null : ['id' => $id, 'linked' => isLinked($id)];
    },
    'onLinked' => fn ($id, array $user) => saveLink($id, $user['address']),
]);
```

**Python · app.py · where you create your app**

```python
def app_user(session):
    user_id = session.get("user_id")
    return {"id": user_id, "linked": is_linked(user_id)} if user_id else None

routes = BlockAuthRoutes(
    os.environ["BLOCKAUTH_API_KEY"],
    os.environ["BLOCKAUTH_API_SECRET"],
    app_url=os.environ["APP_URL"],
    app_user=app_user,
    on_linked=lambda user_id, user: save_link(user_id, user["address"]),
)
```

**.NET · Program.cs**

```csharp
using BlockAuth.Routes;

builder.Services.AddBlockAuth(options =>
{
    options.ApiKey = builder.Configuration["BLOCKAUTH_API_KEY"]!;
    options.ApiSecret = builder.Configuration["BLOCKAUTH_API_SECRET"]!;
    options.AppUrl = builder.Configuration["APP_URL"];
    options.AppUser = async context =>
    {
        var id = context.HttpContext().Session.GetString("user_id");
        return id is null ? null : new BlockAuthAppUser(id, await IsLinkedAsync(id));
    };
    options.OnLinked = (id, user, _) => SaveLinkAsync(id, user.Address);
});
```

> **Placeholders in this code:**
>
> - `isLinked`, `saveLink` are yours: replace them with your app’s own functions (your database, your cache…).
> - `is_linked`, `save_link` are yours: replace them with your app’s own functions (your database, your cache…).

`isLinked` and `saveLink` are yours: they read and write the link in your database. From then on, every Block-Auth login of that user brings your user ID as `externalId` in the [session user](/sdk-integration-spa-session.md#protect-routes): use it to sign them in as **your** user.

### How you add the backend login routes: My own implementation.

**In your backend,** add `GET /link` (is the current user linked?) and `POST /link` (redeems the code passing your user id as `linkExternalId`; answers `409` if it is already linked):

**Node.js · server.js · where you create your Express app**

```javascript
const CONFLICTS = ['Account already linked', 'External id already linked', 'Link conflict']

app.get('/auth/blockauth/link', (req, res) => {
  const appUser = req.session.appUser
  if (!appUser) return res.status(401).json({ error: 'unauthenticated' })
  res.json({ linked: Boolean(appUser.blockauthLinked) })
})

app.post('/auth/blockauth/link', express.json(), async (req, res) => {
  const appUser = req.session.appUser
  if (!appUser) return res.status(401).json({ error: 'unauthenticated' })
  const { code, codeVerifier, redirectUri } = req.body ?? {}
  if (typeof code !== 'string' || typeof codeVerifier !== 'string' || !isOwnUrl(redirectUri)) {
    return res.status(400).json({ error: 'invalid_request' })
  }
  try {
    await blockauth('/auth/token', { code, codeVerifier, redirectUri, linkExternalId: String(appUser.id) })
    appUser.blockauthLinked = true
    res.json({ linked: true })
  } catch (err) {
    if (CONFLICTS.includes(err.message)) return res.status(409).json({ error: 'already_linked' })
    res.status(502).json({ error: 'blockauth_error' })
  }
})
```

**PHP · public/index.php · your entry point**

```php
$conflicts = ['Account already linked', 'External id already linked', 'Link conflict'];

if ($route === 'GET /auth/blockauth/link') {
    $appUser = $_SESSION['app_user'] ?? null;
    if (!$appUser) {
        json(401, ['error' => 'unauthenticated']);
    }
    json(200, ['linked' => (bool) ($appUser['blockauth_linked'] ?? false)]);
}

if ($route === 'POST /auth/blockauth/link') {
    $appUser = $_SESSION['app_user'] ?? null;
    if (!$appUser) {
        json(401, ['error' => 'unauthenticated']);
    }
    $body = json_decode(file_get_contents('php://input'), true) ?: [];
    $redirectUri = $body['redirectUri'] ?? '';
    if (!is_string($body['code'] ?? null) || !is_string($body['codeVerifier'] ?? null) || !isOwnUrl($redirectUri, $appUrl)) {
        json(400, ['error' => 'invalid_request']);
    }
    try {
        $blockauth->exchangeCode($body['code'], $redirectUri, $body['codeVerifier'], (string) $appUser['id']);
    } catch (BlockAuthException $e) {
        json(in_array($e->getMessage(), $conflicts, true) ? 409 : 502, ['error' => 'link_failed']);
    }
    $_SESSION['app_user']['blockauth_linked'] = true;
    json(200, ['linked' => true]);
}
```

**Python · app.py · where you create your app**

```python
CONFLICTS = {"Account already linked", "External id already linked", "Link conflict"}


@app.get("/auth/blockauth/link")
def link_status():
    app_user = session.get("app_user")
    if not app_user:
        return jsonify(error="unauthenticated"), 401
    return jsonify(linked=bool(app_user.get("blockauth_linked")))


@app.post("/auth/blockauth/link")
def link():
    app_user = session.get("app_user")
    if not app_user:
        return jsonify(error="unauthenticated"), 401
    body = request.get_json(silent=True) or {}
    code, verifier, redirect_uri = body.get("code"), body.get("codeVerifier"), body.get("redirectUri")
    if not isinstance(code, str) or not isinstance(verifier, str) or not is_own_url(redirect_uri):
        return jsonify(error="invalid_request"), 400
    try:
        blockauth.exchange_code(code, redirect_uri, code_verifier=verifier, link_external_id=str(app_user["id"]))
    except BlockAuthError as error:
        return jsonify(error="link_failed"), 409 if str(error) in CONFLICTS else 502
    session["app_user"] = {**app_user, "blockauth_linked": True}
    return jsonify(linked=True)
```

**.NET · Program.cs**

```csharp
string[] conflicts = ["Account already linked", "External id already linked", "Link conflict"];

app.MapGet("/auth/blockauth/link", (HttpContext http) =>
{
    var appUserId = http.Session.GetString("app_user_id");
    if (appUserId is null) return Results.Json(new { error = "unauthenticated" }, statusCode: 401);
    return Results.Ok(new { linked = http.Session.GetString("blockauth_linked") == "true" });
});

app.MapPost("/auth/blockauth/link", async (CodeRequest body, HttpContext http, AuthCodeClient blockauth) =>
{
    var appUserId = http.Session.GetString("app_user_id");
    if (appUserId is null) return Results.Json(new { error = "unauthenticated" }, statusCode: 401);
    if (string.IsNullOrEmpty(body.Code) || string.IsNullOrEmpty(body.CodeVerifier) || !IsOwnUrl(body.RedirectUri))
        return Results.BadRequest(new { error = "invalid_request" });
    try
    {
        await blockauth.ExchangeCodeAsync(body.Code, body.RedirectUri!, body.CodeVerifier, appUserId);
        http.Session.SetString("blockauth_linked", "true");
        return Results.Ok(new { linked = true });
    }
    catch (BlockAuthException e)
    {
        return Results.Json(new { error = "link_failed" }, statusCode: conflicts.Contains(e.Message) ? 409 : 502);
    }
});
```

Ask for a recent login before linking (for example, in the last 10 minutes). To remove a link from your side, call `revokeLink(externalId)`; when a user unlinks from Block-Auth Identity you get the `account.unlinked` webhook.

## Show your UI based on roles (optional)

Not needed for the login to work. If your UI changes with the roles you assign in the Dashboard, read the user with `useBlockAuthUser()` in React and Vue, or with the `BlockAuthService` signals in Angular, and check their roles with `hasRoleBySlug(slug)`. You have the example for each framework in [Roles](/sdk-roles.md#frontend), along with how to [protect your backend](/sdk-roles.md#backend) by role.

## Read app data from your server (optional, Node.js)

The browser SDK above never needs `apiSecret`. Administrative operations — reading your app model, users, roles and logs — run on **your own server** with the `BlockAuthProvider` of `@block-auth.io/core`, 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.

```javascript
// server.js — runs on YOUR Node backend (CommonJS), never bundled into the frontend
const { BlockAuthProvider } = require("@block-auth.io/core");

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

async function main() {
  // 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
  const users = await provider.users(); // your app's users and their roles
}
```

> **Note:** On Node, load the SDK with `require`. Importing it with `import` from an ES
> module currently fails with `Named export 'SHA256' not found`.

To know **which user** logged in, don't use these calls with an address sent by your frontend: use the routes from [backend routes](/sdk-integration-spa-backend.md#backend-routes), where your backend gets the address from Block-Auth.
