# Block-Auth integration guide: React + Vite · Node.js

> Block-Auth is passwordless login for your app with a decentralized identity. Your frontend opens the Block-Auth login (a widget for React, Vue or Angular, or a redirect from your backend, or the WordPress plugin), and your backend redeems a one-time code with its API Secret to get a verified user and create its own session.

Only the steps for React + Vite · Node.js, in order. Follow all of them, then go over the integration checklist at the end. The full documentation is in [llms.txt](/llms.txt).

## Status

Updated on 2026-11-27. Latest published packages: `@block-auth.io/react` 0.13.0, `@block-auth.io/vue` 0.10.0, `@block-auth.io/angular` 0.10.0, `@block-auth.io/core` 0.21.0, `@block-auth.io/node` 0.1.0, `blockauth/sdk` 0.6.0, `blockauth-sdk` 0.6.0, `BlockAuth.Sdk` 0.5.0. Not published yet, so don’t install them even if a page names them: `BlockAuth.Sdk.AspNetCore`.

Known limitations:

- Next.js: build with Turbopack (the default in Next.js 16). With webpack (Next.js 15, or `next build --webpack`) the build fails today.
- Create React App: the build warns `Can't resolve '@walletconnect/ethereum-provider'`, an optional dependency the widget doesn't use. Build with `CI=false`, because `CI=true` turns the warning into an error.

---

# React, Vue or Angular

Follow this guide if your frontend is a React, Vue or Angular app. At the end your users sign in with Block-Auth and your backend has a verified session for them.

## What you'll build

You need **two pieces**, and this guide covers both:

- **In your frontend:** the Block-Auth widget (`@block-auth.io/react`, `/vue` or `/angular`). It shows the sign-in button and opens the login.
- **In your backend:** three routes that redeem the login code with your API secret. Your backend can be in any language: the examples are in Node.js, PHP, Python and .NET.

The browser never decides who the user is: the widget only passes a one-time code to your backend, and your backend gets the user from Block-Auth.

1. Your frontend → Block-Auth: Login in a popup (PKCE)
2. Block-Auth → Your frontend: One-time code
3. Your frontend → Your backend: `POST /code`
4. Your backend → Block-Auth: `POST /api/auth/token`
5. Block-Auth → Your backend: `{ address, roles }`
6. Your backend → Your frontend: httpOnly session cookie
7. Your frontend → Your backend: `GET /me`
8. Your backend → Your frontend: `{ address, roles }`

## Prepare your app

1. In the Dashboard, create your application following the [Integration Quickstart](/integration-quickstart.md#applications). As the domain, enter the host where your **frontend** runs (for example `your-app.com`).
2. Pick the keys based on where your app is going to run. Each environment has its own in [Applications » Integration details](/integration-quickstart.md#apps-retrieve-keys), and they don't mix:

| Where your app runs         | Which keys to use                                                                                                    | Where you put them                  |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| Your computer (`localhost`) | The **Development** ones. They work right away.                                                                      | The `.env` on your computer         |
| Your live server            | The **Production** ones. They work once you [validate your domain](/integration-quickstart.md#apps-validate-domain). | Your server's environment variables |

3. Fill in your data once in the [SDK Quickstart](/sdk-integration.md#setup): from then on, each guide gives you the files and code already adapted to your app.

---

# Your frontend

Install and set up the Block-Auth widget in your React, Vue or Angular app.

## Your environment variables

Before you touch any code, create the `.env` files for your frontend and your backend. Your `apiKey` is public and goes in the frontend; your `apiSecret` goes only in the backend. Here they are with your data:

#### Vite (React · Vue) · development

This is your frontend’s `.env`. The backend has its own file.

**.env, next to the frontend package.json**

```dotenv
VITE_BLOCKAUTH_API_KEY=your_api_key
```

#### Vite (React · Vue) · production

It’s baked into the build, so it must exist where you build for production. Pick how you build:

**File · .env.production · in your frontend folder**

```dotenv
VITE_BLOCKAUTH_API_KEY=your_api_key
```

**Docker · Dockerfile · right before npm run build**

```dotenv
ARG VITE_BLOCKAUTH_API_KEY
RUN npm run build
```

**Docker · docker-compose.yml · in the service that builds your frontend**

```dotenv
build:
  args:
    VITE_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY}
```

**CI · Variable of your CI · in the job that runs npm run build**

```dotenv
VITE_BLOCKAUTH_API_KEY=your_api_key
```

In the widget config, read the apiKey from that variable instead of writing `your_api_key`:

- Vite (`src/main.jsx · src/main.ts`): `apiKey: import.meta.env.VITE_BLOCKAUTH_API_KEY,`

> **Placeholders in this code:**
>
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.

`APP_URL` in development is the URL where your frontend runs: Vite `http://localhost:5173`.

#### Node.js · development

In a .env next to your backend package.json. Load it with `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file).

**Your backend’s .env · in your backend folder**

```dotenv
APP_URL=http://localhost:5173
BLOCKAUTH_API_KEY=your_api_key
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
SESSION_SECRET=<generate one: openssl rand -hex 32>
```

#### Node.js · production

Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code.

**Environment variables on your server**

```dotenv
APP_URL=https://your-app.com
BLOCKAUTH_API_KEY=your_api_key
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
SESSION_SECRET=<generate one: openssl rand -hex 32>
```

> **Placeholders in this code:**
>
> - Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site.
> - Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`.
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.
> - Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you.

## Install the widget

Run it in your **frontend** folder, the one that already has the `package.json` of your React, Vue or Angular app. If your frontend is in a subfolder, like `frontend/` or `client/`, go into it first. If frontend and backend share one `package.json`, it's the project root:

**React · Terminal · in your frontend package.json folder**

```bash
npm install @block-auth.io/react
```

Check that the package shows up in that `package.json`. If npm created a new `package.json`, you were in another folder: delete it along with its `node_modules` and run the install again in your frontend folder.

**Angular:** the widget brings wallet libraries with CommonJS modules and optional dependencies the Angular builder can't resolve. Add them to the build options in `angular.json`, or the build warns and fails. Also raise the `initial` budget of the production build: the wallets add about 1 MB and the default limit of new Angular projects (1 MB) stops `ng build`. If your `angular.json` already has `budgets`, change only the `initial` one. Select the **Angular** tab to see the configuration.

## Configure the widget

Add it once, in the file where your app starts: `src/main.jsx` in React with Vite (`src/index.js` with CRA), `src/main.ts` (or `src/main.js`) in Vue and `app.config.ts` in Angular. Your app doesn't change: in React you wrap it as is, with everything it already has inside, and in Vue you add the `.use()` to the chain you already have (for example, next to `.use(router)`), before `.mount()`.

**React · src/main.jsx · where your app starts**

```jsx
import { createRoot } from 'react-dom/client'
import { BlockAuthProvider } from '@block-auth.io/react'
import { App } from './App'

const config = {
  apiKey: 'your_api_key',
  locale: 'en',
}

createRoot(document.getElementById('root')).render(
  <BlockAuthProvider config={config}>
    <App />
  </BlockAuthProvider>,
)
```

> **Placeholders in this code:**
>
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.

> **Note:** Never put the `apiSecret` in your frontend, not even in an environment
> variable like `VITE_…` or `NEXT_PUBLIC_…`: the bundler copies it into the
> JavaScript every visitor downloads. The widget doesn't need it: if you pass
> it, the SDK sends it from the browser.

### Config options

- `apiKey` _(string, required)_: your app's API key. It's public: it only says which app is calling.
- `authEndpoint` _(string | false)_: base path of your [backend routes](/sdk-integration-spa-backend.md#backend-routes). By default `/auth/blockauth`: set it only if your routes live under another path, and set the same path as `basePath` in your backend package. To turn off a package route you don’t use, pass `routes: { link: false }` (in .NET, `DisabledRoutes`). Serve it from the same origin as your frontend, so the session cookie travels with every request. If a route is missing or doesn't answer, the browser console says what to fix. Set it to `false` only if your app has no backend: the widget then signs the user in by itself, and your page knows their address but your server has no session it can trust.
- `locale` _(string)_: language of the widget, `"en"` or `"es"`. By default, the browser's language.
- `sessionCheckSeconds` _(number)_: how often the widget asks `/me` whether the session is still open, besides every time the tab gets focus. By default `60`; `0` turns it off.
- `onSessionEnded` _(function)_: called when your backend has closed the session, for example after the user signed out from Block-Auth Identity or the extension. The widget already shows the user as signed out: use it to leave private pages.
- `wsUrl` _(string)_: the Block-Auth server the widget talks to. By default production (`wss://wss.block-auth.io`): change it only if Block-Auth gives you another environment to test against.

The login itself happens on the Block-Auth login page (`auth.block-auth.io`), so you don't configure Google, Microsoft, wallets or WalletConnect in your app.

> Your app today: this page covers “It already has a login” or “It has no login”. Both variants are written out below, each one marked. Follow only the one that matches the app.

## Add the login button

### Your app today: It already has a login.

Put `FlowBlockAuth` on your login page, below your form, as another way in. **Don't replace your page:** add only the `FlowBlockAuth` import and the component right after your form (in Vue and Angular, also the `onSuccess` and `onError` functions). In the example, the `<form>` is your current form, which stays the same. After the login, reload the page: your app asks your backend again who the user is, and your backend resolves it with [your session or Block-Auth's](/sdk-integration-spa-session.md#protect-routes).

**React · Example · your login page with the button added**

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

export function LoginPage() {
  return (
    <main>
      <form method="post" action="/login">
        <input name="email" type="email" />
        <input name="password" type="password" />
        <button type="submit">Sign in</button>
      </form>
      <FlowBlockAuth
        onSuccess={() => window.location.assign('/')}
        onError={() => alert('Sign-in failed, try again.')}
      />
    </main>
  )
}
```

**When signing out**, also close the Block-Auth session: in the function where you already sign out, add a call to `POST /auth/blockauth/logout` with a JSON `{}` body. It works the same in React, Vue and Angular. In the example, `/api/logout` is your current logout, which stays the same:

**Logout · Example · your logout function with the call added**

```javascript
async function logout() {
  await fetch('/api/logout', { method: 'POST' })
  await fetch('/auth/blockauth/logout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: '{}',
  })
  window.location.assign('/login')
}
```

To let your current users reach their same account, [link them](/sdk-integration-spa-extras.md#link-users).

### Your app today: It has no login.

Place `FlowBlockAuth` where you want the sign-in button. After the login it turns into the profile menu, and on reload it restores the session by asking your backend.

**React · Your header · e.g. src/components/Header.jsx**

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

export function Header() {
  return (
    <header>
      <FlowBlockAuth
        onSuccess={(address) => console.log('Signed in as', address)}
        onError={() => alert('Sign-in failed, try again.')}
        onLogout={() => window.location.assign('/')}
      />
    </header>
  )
}
```

If the browser blocks the popup, the widget opens the login in the same tab: Block-Auth sends the user back to the root of your app (`/`), which must load your frontend with the widget config, and the widget finishes the login on the page where it started.

**Does your server send a `Content-Security-Policy`?** You won’t notice in development, but in production it blocks the widget: unstyled button, broken logo and failed login. When you deploy, allow it as explained in [Go live](/sdk-integration-spa-go-live.md#production-csp).

## Checklist

Go over these before moving on to the backend. They adapt to your framework and your choices:

The checklist depends on the framework and the choices. Every combination is listed below.

#### React · Vite

- **The package is installed**: `@block-auth.io/react` shows up in your frontend `package.json`, not in a new one created elsewhere.
- **`BlockAuthProvider` wraps your whole app**: in `src/main.jsx`.
- If the apiKey is in an environment variable: **Your apiKey comes from `VITE_BLOCKAUTH_API_KEY`**: in `.env`, read with `import.meta.env.VITE_BLOCKAUTH_API_KEY`. If a change doesn’t apply, restart `npm run dev`.
- If the apiKey is written in the widget config: **Your apiKey is in the widget config**: replacing `your_api_key`.
- If “Your app today” is “It already has a login”: **The button sits next to your login form**: `<FlowBlockAuth />` on your login page, reloading the page in `onSuccess`.
- If “Your app today” is “It has no login”: **The button is where you want it**: `<FlowBlockAuth />`, for example in your header.
- If “Your app today” is “It already has a login”: **Your logout also closes the Block-Auth session**: with a `POST /auth/blockauth/logout` and a JSON `{}` body, after your own logout.
- If “Your app today” is “It has no login”: **The widget handles the logout**: after the login the button becomes the profile menu, with its own sign out.
- If the apiKey is in an environment variable: **The `apiSecret` isn’t in the frontend**: not even in a `VITE_…` variable: it only goes in your backend.
- If the apiKey is written in the widget config: **The `apiSecret` isn’t in the frontend**: in no frontend file or config: it only goes in your backend.

Login doesn’t work yet: your backend is missing. You test it end to end in the last step, [Connect and try it](/sdk-integration-spa-connect.md#try-it).

---

# Your backend

Add the routes the widget calls and receive webhooks. With the Block-Auth package for your server it's mostly configuration: it redeems the login code, keeps the session and verifies the webhooks for you. If you prefer, you can write it yourself.

## Your environment variables

Your backend reads these variables. Here they are with your data:

`APP_URL` in development is the URL where your frontend runs: Vite `http://localhost:5173`.

#### Node.js · development

In a .env next to your backend package.json. Load it with `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file).

**Your backend’s .env · in your backend folder**

```dotenv
APP_URL=http://localhost:5173
BLOCKAUTH_API_KEY=your_api_key
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
SESSION_SECRET=<generate one: openssl rand -hex 32>
```

#### Node.js · production

Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code.

**Environment variables on your server**

```dotenv
APP_URL=https://your-app.com
BLOCKAUTH_API_KEY=your_api_key
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
SESSION_SECRET=<generate one: openssl rand -hex 32>
```

> **Placeholders in this code:**
>
> - Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site.
> - Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`.
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.
> - Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you.

## Add the backend routes

### 1. Install the package

Run it next to your backend’s `package.json` (if your frontend and backend share one project, at the root):

**Node.js · Terminal · next to your backend package.json**

```bash
npm install @block-auth.io/node
```

### Your app today: It already has a login.

The package works with Express and `express-session`. Check your `package.json` dependencies: if you already have both, skip this. If one is missing, install it: `npm install express express-session`.

### Your app today: It has no login.

The package works with Express and `express-session`. If your server doesn’t have them yet, install them too: `npm install express express-session`.

### 2. Add it to your server

This is **everything you add** to your server, in three parts. Your app, your session and your server start-up stay as they are.

**a. The imports**, at the top of the file where you create your app, next to the ones you already have:

**Node.js · Top of the file · with your imports**

```javascript
import { BlockAuthRoutes } from '@block-auth.io/node'
import { blockauthRouter } from '@block-auth.io/node/express'
```

**b. Create `routes`.** Don’t paste your keys here: the block reads them from the `.env` you filled in under “Your environment variables”, so the API Secret never ends up in your code. Where it goes, right below the block:

**Node.js · Below const app = express()**

```javascript
export const routes = new BlockAuthRoutes({
  apiKey: process.env.BLOCKAUTH_API_KEY,
  apiSecret: process.env.BLOCKAUTH_API_SECRET,
  appUrl: process.env.APP_URL,
})
```

**Where to put it:** in the file with `const app = express()`, right below that line. Two adjustments, only if your code looks like this:

- **That line is inside a function**, like `function createApp(config) {`: put the block inside the function, also below it, and drop the `export`. If you leave it outside, importing the file without the variables (from a test, for example) fails with `Set appUrl or allowedOrigins`. If your tests create the app with their own configuration, give them test values too, like `appUrl: 'http://localhost'`, or they fail with that same error.
- **Your app reads `SESSION_SECRET` from a configuration file** (a `config.js`, an `env.ts`, a zod schema…): add `BLOCKAUTH_API_KEY`, `BLOCKAUTH_API_SECRET` and `APP_URL` there too, and in the block change each `process.env.…` to your configuration value (for example, `config.blockauthApiKey`). The block still goes below `const app = express()`.

If you see `Set appUrl or allowedOrigins` on startup, the variables aren’t reaching your server: check that it loads the `.env` (for example, with `node --env-file=.env`, Node 20.6+, or with `import 'dotenv/config'` at the top of your entry file).

**Before mounting it, search for `session(` in your file.** If it’s on its own, in `app.use(session(...))`, change nothing: in step c you put the line right below it. If it’s inside an `app.use('/api', …)` together with other things, like `express.json()`, it only covers `/api` and Block-Auth can’t see it. Split it like this: the session leaves the `app.use('/api', …)` with its options as they are, Block-Auth goes right below it and the rest stays under `/api`:

**Before · Everything together under /api (example only, not to copy)**

```javascript
app.use(
  '/api',
  express.json(),
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, sameSite: 'lax' },
  }),
)
```

**After · The session leaves /api · Block-Auth below**

```javascript
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, sameSite: 'lax' },
  }),
)
app.use(blockauthRouter(routes))
app.use('/api', express.json())
```

**c. Mount it** in your app. This is the part where placement matters most. Put it where `routes` already exists: after step b and in the same place. If you created `routes` inside a function, like `createApp()` or `create_app()`, this line goes inside that same function. In Python that means with the same indentation as the `routes = ...` line; if you paste it against the left margin, it ends up outside the function and Python raises an error:

**Node.js · Right below where you mount session(...)**

```javascript
app.use(blockauthRouter(routes))
```

**Put it before serving your frontend** (`express.static(...)`) **and before any catch-all route** (`app.get('*', …)`). If those come first, they take the widget’s requests and Block-Auth never sees them: you get no error, just a 404 or your app’s HTML.

### 3. Checklist

Go over these before moving on. They’re what most often fails when adding it to an existing app:

**Checklist for Node.js:**

- **The session covers the whole app**: `app.use(session(...))`, not just `/api`.
- **The order is** session → `blockauthRouter` → `express.json()`.
- **You load the `.env`**: `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file).
- **Behind a proxy that terminates `https`**, add `app.set('trust proxy', 1)`.

This only checks that everything is in place. The real test comes in the last step, [Connect and try it](/sdk-integration-spa-connect.md#try-it).

---

# Connect and try it

The last step: make your frontend reach your backend, and check that login works end to end.

## Connect your frontend to your backend

**In development (localhost):**

The widget calls `/auth/blockauth` on the **same origin** as your page, so the session cookie travels with every request. In development your frontend (your App URL) and backend usually run on different ports: proxy those routes to the port your backend already listens on, with your dev server’s proxy:

#### React · Vite

**vite.config.js · at your frontend root · add only server.proxy**

```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: { '/auth/blockauth': 'http://localhost:4000' },
  },
})
```

> Only for development. `4000` is the port your backend already listens on: change it in your data if it isn’t.
>
> Use the port your backend already listens on. Defaults in the examples: Node.js `4000`.

This isn’t used in production: with Production in your settings, this section shows how to serve it from your domain.

**In production (your domain):**

The widget calls `/auth/blockauth` on the **same origin** as your page, so the session cookie travels with every request. In production you get that by serving everything from your domain, in one of these two ways:

- **Your backend serves the frontend build.** Build it (`npm run build`) and have your backend serve that folder. Nothing else needed.
- **Frontend and backend run separately.** Your reverse proxy sends `/auth/blockauth` to your backend. For example, with Nginx:

**Nginx · Your web server · add the location to your server block**

```nginx
server {
  server_name your-app.com;

  location /auth/blockauth/ {
    proxy_pass http://127.0.0.1:4000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}
```

> **Placeholders in this code:**
>
> - Replace `your-app.com` with your domain, or fill in your data in the SDK Quickstart and it is filled in for you.
> - `127.0.0.1` is your own server: change it if your backend runs on another machine. The port is the Backend port from your data, the one your server already uses.

With `https` on a proxy in front, your backend must know it to send the secure cookie: see [Go live](/sdk-integration-spa-go-live.md#production-domain).

## Try it

1. **In development (localhost):** Start your frontend and your backend. **In production (your domain):** Deploy your frontend and your backend on your domain.
2. Open your app, press the Block-Auth button and sign in.
3. Open `https://your-app.com/auth/blockauth/me` in the same browser: it must return your user.

**If it does, it works in development.** The last step is [Go live](/sdk-integration-spa-go-live.md): the same, with your production keys and domain.

If it doesn’t work:

- **You see your app’s page or a `404`**: the request doesn’t reach your backend. Check the connection above and that your backend is running.
- **`401` after signing in**: the login didn’t create the session. Go over your [backend checklist](/sdk-integration-spa-backend.md#server-checks).

---

# Go live

Your code doesn’t change: only the keys, the variables and the domain do. Here are just those changes, with your production data.

Every example on this page uses the production values: the production API Key and API Secret and the app’s real domain.

## What changes

### 1. Validate your domain and use the Production keys

In the Dashboard, [validate your domain](/integration-quickstart.md#apps-validate-domain). Then copy the **Production** data with **Copy data for the guide** and paste it into [your data](/sdk-integration.md#setup): it fills in the Production row.

### 2. Put the variables on your server

In production don’t use your computer’s `.env`: set them as environment variables on your server or platform (Docker, your hosting…). Generate a new `SESSION_SECRET`, different from the development one.

`APP_URL` in development is the URL where your frontend runs: Vite `http://localhost:5173`.

#### Node.js · development

In a .env next to your backend package.json. Load it with `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file).

**Your backend’s .env · in your backend folder**

```dotenv
APP_URL=http://localhost:5173
BLOCKAUTH_API_KEY=your_api_key
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
SESSION_SECRET=<generate one: openssl rand -hex 32>
```

#### Node.js · production

Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code.

**Environment variables on your server**

```dotenv
APP_URL=https://your-app.com
BLOCKAUTH_API_KEY=your_api_key
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
SESSION_SECRET=<generate one: openssl rand -hex 32>
```

> **Placeholders in this code:**
>
> - Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site.
> - Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`.
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.
> - Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you.

Your frontend `apiKey` is baked in at build time: build with the production one.

#### Vite (React · Vue) · development

This is your frontend’s `.env`. The backend has its own file.

**.env, next to the frontend package.json**

```dotenv
VITE_BLOCKAUTH_API_KEY=your_api_key
```

#### Vite (React · Vue) · production

It’s baked into the build, so it must exist where you build for production. Pick how you build:

**File · .env.production · in your frontend folder**

```dotenv
VITE_BLOCKAUTH_API_KEY=your_api_key
```

**Docker · Dockerfile · right before npm run build**

```dotenv
ARG VITE_BLOCKAUTH_API_KEY
RUN npm run build
```

**Docker · docker-compose.yml · in the service that builds your frontend**

```dotenv
build:
  args:
    VITE_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY}
```

**CI · Variable of your CI · in the job that runs npm run build**

```dotenv
VITE_BLOCKAUTH_API_KEY=your_api_key
```

In the widget config, read the apiKey from that variable instead of writing `your_api_key`:

- Vite (`src/main.jsx · src/main.ts`): `apiKey: import.meta.env.VITE_BLOCKAUTH_API_KEY,`

> **Placeholders in this code:**
>
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.

### 3. Serve everything from your domain, over `https`

There’s no dev proxy in production. Either your backend serves the frontend build, or your reverse proxy (Nginx, your load balancer) sends `/auth/blockauth` to your backend. Then make sure the session cookie is marked secure. The examples without the package already do it from `APP_URL`; with the package, it depends on your backend:

- In your `session(...)`, add `secure: true` to `cookie`.
- If a proxy terminates `https` in front of your backend, add `app.set('trust proxy', 1)`. Without it, Express doesn’t send the secure cookie and `/me` answers `401`.

### 4. Allow the widget in your Content Security Policy

If your server sends a `Content-Security-Policy` header (many frameworks, proxies and security templates add one), the browser blocks the widget until you allow it. You won't notice in development, because the frontend dev server doesn't send it: it shows up after deploying, with an unstyled button, a broken logo and a failing login. Check with `curl -sI https://your-domain | grep -i content-security-policy`; if it returns nothing, skip this step.

Add these directives to the CSP you already send, keeping yours. If you already have one of them, add only the missing sources: **If you set `wsUrl`** (another Block-Auth server), write its host instead of `wss.block-auth.io` in `connect-src`, over `https` and `wss`.

**Content-Security-Policy · HTTP header your server sends**

```text
connect-src 'self' https://wss.block-auth.io wss://wss.block-auth.io;
img-src 'self' data:;
style-src 'self' 'unsafe-inline';
```

- `connect-src`: the widget asks `wss.block-auth.io` for the login link, over `https` and `wss`; `'self'` covers your `authEndpoint`.
- `img-src`: the Block-Auth logo in the button, embedded as a `data:` image.
- `style-src`: the widget injects its styles in a `<style>` tag. It only allows inline CSS, not JavaScript: `script-src` can stay as strict as you have it.

The login opens on `auth.block-auth.io`, in a popup or in the same tab if the browser blocks popups, so you don't need to allow Google, Microsoft or the wallets. If your site sends `Cross-Origin-Opener-Policy`, use `same-origin-allow-popups`, not `same-origin`: otherwise your page can't receive the result from the popup.

### 5. Check the webhook, if you use it

In your production app in the Dashboard, the [webhook](/sdk-integration-spa-webhooks.md) path is the same, `/auth/blockauth/webhook`, on your public domain.

### 6. Try it

Same as in development, but on your domain: sign in with the Block-Auth button and open `https://your-app.com/auth/blockauth/me`. It must return your user. If the button has no styles, a broken logo, or the login says it failed, open the browser console (F12): a `violates the following Content Security Policy directive` message means step 4 is missing.

## Before you publish

Go over this before opening your app to your users:

- Your production app has its own validated domain and keys, and the site uses `https`.
- The `apiSecret` is only in your backend's environment, never in the frontend bundle.
- `/code` checks that `redirectUri` is on your origin, and your app creates sessions only from the address returned by `/api/auth/token`.
- The session cookie is `HttpOnly`, `Secure` and `SameSite=Lax`.
- If your server sends a CSP, allow the widget as in [step 4](#production-csp), and if it sends `Cross-Origin-Opener-Policy`, it's `same-origin-allow-popups`.

**With this, the integration is done.** What follows under **More options** is optional: add it when your app needs it.

## What the package already covers

If you use the Block-Auth package in your backend, it already does this for you:

- **Trusts only Block-Auth.** The user always comes from redeeming the code with your `apiSecret`, and the `redirectUri` must be on `appUrl`. If your frontend lives on several origins, pass `allowedOrigins` (a list) instead.
- **Blocks forged requests.** It only accepts `POST` requests with a JSON body, so another site can't log your users in with a form.
- **Keeps the session short and clean.** It renews the session ID on every login and ends it when the user's Block-Auth signature expires (`signedExpiredAt`). To end it earlier, set `maxSessionSeconds` (`MaxSessionDuration` in .NET).
- **Logs out everywhere.** `POST /logout` also closes the user's Block-Auth sessions for your app, and keeps the rest of your session data.
- **Verifies every webhook.** Signature, time and `apiKey`, before calling your code.

---

# Integration checklist

Go over it before calling your integration done, whichever guide you follow: the security rules it must keep, the example values to replace and how to check that it works.

## Security rules

Your integration must keep all these rules. Each one is explained in the guides and in [Security](/security.md).

- **The API Secret only lives in the backend.** Read it from an environment variable or your secret store. Never put it in frontend code, in a `VITE_`, `NEXT_PUBLIC_` or `REACT_APP_` variable, in Angular's `environment.ts`, in a committed file or in a log. The API Key is public and goes in the frontend.
- **The browser never decides who the user is.** The widget only hands a one-time code to the backend. The backend redeems it at `POST /api/auth/token` with the API Secret (the Block-Auth packages do it for you) and only then creates its own session. Never trust a user or address sent by the browser.
- **With the Node.js package, the order matters.** Mount `blockauthRouter(routes)` after `session(...)` and before `express.json()`, and make the session cover `/auth/blockauth`, not only `/api`.
- **The widget calls `/auth/blockauth` on the same origin as the page.** In development, use your dev server's proxy. In production, serve the frontend from the backend or send `/auth/blockauth` to it with a reverse proxy, over `https`. Don't open CORS for it.
- **With the redirect login, check `state`** before redeeming the code.
- **Verify every webhook** before trusting it: the Block-Auth packages do it, and the [Webhooks](/webhooks.md) page explains how to do it yourself.
- **Use role slugs, not names.** Role names can change; slugs never do.
- **Don't let the session outlive `signedExpiredAt`**, the moment the user's signature for the app expires ([how long a session lasts](/security.md#session)).
- **Frontend only (`authEndpoint: false`) only shows who is signed in.** There's no backend redeeming the code, so the rules about the backend and `/auth/blockauth` don't apply to it, but no server has a session it can trust either. Never use the address the page knows to authorize anything on a server: if the app has an API or private data, follow [React, Vue or Angular (+ backend)](/sdk-integration-spa.md).

## Placeholders

The code in the docs uses these placeholders. Replace every one before finishing, and never with a made-up value:

| Placeholder                                                                                                                                                      | What to do                                                                                                                     |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `sha256_hex_of_your_api_secret`, `sha256_of_api_secret`                                                                                                          | Replace the `sha256_…` value with the SHA-256 hash (hex) of your API Secret. Compute it on your computer, never on a web page. |
| `your_api_secret`, `<pega el API Secret del Dashboard>`, `<paste the API Secret from the Dashboard>`                                                             | Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site.      |
| `a_long_random_string`, `<genera uno: openssl rand -hex 32>`, `<generate one: openssl rand -hex 32>`                                                             | Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`.                |
| `your_api_key`                                                                                                                                                   | Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.              |
| `https://your-app.com`                                                                                                                                           | Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you.      |
| `your-app.com`                                                                                                                                                   | Replace `your-app.com` with your domain, or fill in your data in the SDK Quickstart and it is filled in for you.               |
| `https://example.com`                                                                                                                                            | Replace `https://example.com` with your app’s validated domain.                                                                |
| `https://your-site.com`                                                                                                                                          | Replace `https://your-site.com` with your WordPress site URL.                                                                  |
| `acme-x7k2p9`                                                                                                                                                    | Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name.    |
| `"your-app": {`                                                                                                                                                  | Replace `your-app` with your project name: the key you already have under `projects` in your `angular.json`.                   |
| `your_access_token`                                                                                                                                              | Replace `your_access_token` with the access token you get from `/api/signin`. It lasts 1 hour.                                 |
| `your_refresh_token`                                                                                                                                             | Replace `your_refresh_token` with the refresh token you got from `/api/signin`.                                                |
| `code_from_the_widget`, `code_verifier_from_the_widget`, `redirect_uri_from_the_widget`                                                                          | Replace the `…_from_the_widget` values with the ones the widget sends to your `/code` route.                                   |
| `code_from_your_callback`                                                                                                                                        | Replace `code_from_your_callback` with the `code` Block-Auth sends to your callback URL.                                       |
| `"your-app"`                                                                                                                                                     | Replace `your-app` with your project name in `angular.json`.                                                                   |
| `findUser`, `saveSignout`, `lastSignout`, `removeLink`, `endSessionsOf`, `markUnlinked`, `alreadyProcessed`, `isLinked`, `saveLink`, `listOrders`, `deleteOrder` | `findUser`, `saveSignout`… are yours: replace them with your app’s own functions (your database, your cache…).                 |

## Definition of done

The integration is done when the last Quickstart step, Go live, passes on your domain. Before that, the same check must pass in development:

- **React, Vue or Angular:** after signing in with the Block-Auth button, `GET /auth/blockauth/me` in the same browser returns the user. A `404` or your app's page means the request doesn't reach the backend; a `401` means the login didn't create the session. See [Connect and try it](/sdk-integration-spa-connect.md#try-it).
- **React, Vue or Angular, frontend only:** after signing in with the Block-Auth button, it turns into the profile menu, and the user is still signed in after reloading the page. See [Try it](/sdk-integration-frontend-try.md).
- **PHP, Python, .NET, Node.js:** opening `/blockauth/login` and signing in brings the user back signed in, and `GET /api/me` returns them. See [Login](/sdk-integration-server-login.md#try-it).
- **WordPress:** after signing out, the Block-Auth button on `/wp-login.php` signs the user in to WordPress. See [Connect it](/sdk-integration-wordpress-connect.md#try-it).

Also check that the API Secret doesn't appear anywhere in the frontend build output or in the repository, and that the app's own lint and tests still pass.

## For AI assistants

If an AI assistant (Claude Code, Cursor, Copilot, ChatGPT…) does the integration, give it the docs in Markdown. The website shows one framework, backend or environment at a time; the Markdown has every variant at once:

- [`/llms.txt`](/llms.txt): the index of every page, with the guides in order.
- [`/llms-full.txt`](/llms-full.txt): every page in a single file.
- `/llms/<stack>.md`: one guide per stack (for example [`/llms/react-vite-node.md`](/llms/react-vite-node.md)), with only its steps, in order. The list is in `/llms.txt`.
- Any page with `.md` added to its path, for example [`/sdk-integration-spa-backend.md`](/sdk-integration-spa-backend.md). Each page also points to it with `<link rel="alternate" type="text/markdown">`.

In the Markdown versions every tab and option is written out and marked (for example, _Only for Node.js_ or _In production_), and the code keeps its placeholders. Follow only the variant that matches the app.

### Working with the developer

Before writing code, find out or ask:

- The stack: frontend framework and build tool, backend language and framework, whether frontend and backend share one project.
- Whether the app already has its own login, and where its session and its "who am I" route live.
- The port the backend already listens on, and the URL where the frontend opens (the App URL).
- Whether the app already exists in the Block-Auth Dashboard, and its API Key (public). Development and production have different keys.

Never ask for the API Secret or the `SESSION_SECRET` in the conversation, and never write them into code or commit them. Tell the developer which environment variable to set and how to generate `SESSION_SECRET` (`openssl rand -hex 32`), and check that `.env` is in `.gitignore`.

While implementing:

- Read the existing server first: where the app is created, its session, its body parsers, how it loads variables and how its tests build it. Add the Block-Auth lines into that structure instead of replacing it with the examples' full server.
- Keep every Block-Auth value in the app's existing configuration (for example its config module), not scattered `process.env` reads.
- Keep the app's lint and tests passing; give the tests test values, never real keys.

When you finish, tell the developer: the files you changed, the variables they must set and where, the exact steps to try it (the definition of done above) and the optional next steps (webhooks, using the session in their routes, going live). If something fails, ask for the exact error line from the browser console and the backend console, with a `logger` passed to `BlockAuthRoutes`, and match it in [Troubleshooting](/troubleshooting.md).

---

# Optional pages

Add them only when the app needs them. They show every framework and backend.

- [React, Vue or Angular: use the session in your routes](/sdk-integration-spa-session.md): Read the Block-Auth user in your backend to protect routes and check roles.
- [React, Vue or Angular: receive webhooks](/sdk-integration-spa-webhooks.md): Close the session in your app when the user closes it from Block-Auth.
- [React, Vue or Angular: customize the widget](/sdk-integration-spa-customize.md): Callbacks, behavior and styles of the Block-Auth login button.
- [React, Vue or Angular: link users and more](/sdk-integration-spa-extras.md): Link the users you already have, show your UI based on their roles and read your app data from your server.
