---
title: "React, Vue or Angular: your backend"
description: "Add the routes the widget calls and receive webhooks, with the Block-Auth package for your server or with your own implementation."
url: "/sdk-integration-spa-backend/"
language: "en"
guide: "React, Vue, Angular (+ backend)"
step: "Quickstart step 2 of 4, required"
---

# 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`, Next.js `http://localhost:3000`, Create React App `http://localhost:3000`, Angular `http://localhost:4200`.

#### 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>
```

#### PHP · development

getenv() doesn't read .env files by itself: set them in your server (`SetEnv` in Apache, `env[]` in PHP-FPM), or load the .env with `vlucas/phpdotenv`.

**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>
```

#### PHP · 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>
```

#### Python (Flask) · development

In a .env in your backend folder. `flask run` loads it if `python-dotenv` is installed; with `python app.py`, gunicorn or waitress, call `load_dotenv()` first, use `uv run --env-file .env …` or export the variables.

**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>
```

#### Python (Flask) · 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>
```

#### Python (FastAPI) · development

In a .env in your backend folder. Start uvicorn with `--env-file .env` (needs `python-dotenv` installed) or, with uv, `uv run --env-file .env uvicorn …`, or export the variables.

**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>
```

#### Python (FastAPI) · 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>
```

#### .NET · development

The public values go in `appsettings.json`. The secret never goes in a file you commit: in development use `user-secrets`, in production an environment variable.

**appsettings.json**

```json
{
  "APP_URL": "http://localhost:5173",
  "BLOCKAUTH_API_KEY": "your_api_key"
}
```

**Terminal, in the project folder (development only)**

```bash
dotnet user-secrets init
dotnet user-secrets set "BLOCKAUTH_API_SECRET" "<paste the API Secret from the Dashboard>"
```

#### .NET · production

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

**appsettings.json**

```json
{
  "APP_URL": "https://your-app.com",
  "BLOCKAUTH_API_KEY": "your_api_key"
}
```

**Environment variable on your server (never in a repo file)**

```dotenv
BLOCKAUTH_API_SECRET=<paste the API Secret from the Dashboard>
```

> **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.

> 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.

## Add the backend routes

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

### 1. Install the package

**Only for Node.js:**

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
```

**Only for PHP:**

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

**PHP · Terminal · next to your backend composer.json**

```bash
composer require blockauth/sdk
```

**Only for .NET:**

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

**.NET · Terminal · next to your backend .csproj**

```bash
dotnet add package BlockAuth.Sdk.AspNetCore
```

**Only for Python (Flask):**

**Only for pip:**

Run it next to your backend’s `requirements.txt`, with its virtual environment active (if your frontend and backend share one project, at the root):

**Python (Flask) · Terminal · next to your backend requirements.txt**

```bash
source .venv/bin/activate
pip install "blockauth-sdk[flask]"
```

Also add `blockauth-sdk[flask]` (without quotes) to your `requirements.txt` so your deployment installs it. If `pip` answers `externally-managed-environment`, your backend’s virtual environment isn’t active.

**Only for uv:**

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

**Python (Flask) · Terminal · next to your backend pyproject.toml**

```bash
uv add "blockauth-sdk[flask]"
```

`uv add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it.

**Only for Poetry:**

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

**Python (Flask) · Terminal · next to your backend pyproject.toml**

```bash
poetry add "blockauth-sdk[flask]"
```

`poetry add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it.

**Only for Python (FastAPI):**

**Only for pip:**

Run it next to your backend’s `requirements.txt`, with its virtual environment active (if your frontend and backend share one project, at the root):

**Python (FastAPI) · Terminal · next to your backend requirements.txt**

```bash
source .venv/bin/activate
pip install "blockauth-sdk[fastapi]"
```

Also add `blockauth-sdk[fastapi]` (without quotes) to your `requirements.txt` so your deployment installs it. If `pip` answers `externally-managed-environment`, your backend’s virtual environment isn’t active.

**Only for uv:**

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

**Python (FastAPI) · Terminal · next to your backend pyproject.toml**

```bash
uv add "blockauth-sdk[fastapi]"
```

`uv add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it.

**Only for Poetry:**

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

**Python (FastAPI) · Terminal · next to your backend pyproject.toml**

```bash
poetry add "blockauth-sdk[fastapi]"
```

`poetry add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it.

**Only for Node.js:**

### 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`.

**Only for Python (Flask):**

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

The package keeps the user in Flask’s session, which needs `app.secret_key`. Search your code for `secret_key`: if your app already sets it, skip this and the package will use that same session. If not, add `app.secret_key = os.environ["SESSION_SECRET"]` right after `app = Flask(...)`.

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

The package keeps the user in Flask’s session, which needs `app.secret_key`. If your app doesn’t set it yet, add `app.secret_key = os.environ["SESSION_SECRET"]` right after `app = Flask(...)`.

**Only for Python (FastAPI):**

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

The package keeps the user in Starlette’s session. Search your code for `SessionMiddleware`: if your app already adds it, skip this and the block below, because the package will use that same session. If not, add it right after `app = FastAPI()`:

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

The package keeps the user in Starlette’s session. If your app doesn’t have `SessionMiddleware` yet, add it right after `app = FastAPI()`:

**Python (FastAPI) · Only if you don’t have it · right after app = FastAPI()**

```python
from starlette.middleware.sessions import SessionMiddleware

app.add_middleware(
    SessionMiddleware,
    secret_key=os.environ["SESSION_SECRET"],
    same_site="lax",
    https_only=os.environ["APP_URL"].startswith("https"),
)
```

### 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'
```

**PHP · public/index.php · at the top, after the autoload**

```php
use BlockAuth\Routes\BlockAuthRoutes;
```

**Python (Flask) · Top of the file · with your imports**

```python
import os

from blockauth_sdk import BlockAuthRoutes
from blockauth_sdk.routes.flask import blockauth_blueprint
```

**Python (FastAPI) · Top of the file · with your imports**

```python
import os

from blockauth_sdk import BlockAuthRoutes
from blockauth_sdk.routes.fastapi import blockauth_router
```

**.NET · Program.cs · at the very top**

```csharp
using BlockAuth.AspNetCore;
```

**Only for Python (Flask), Python (FastAPI):**

You only need `import os` if step b reads the keys with `os.environ`. If your app reads them from its own configuration file (a `config.py`, a `Settings` class…), don’t add it.

**Only for Node.js, PHP, Python (Flask), Python (FastAPI):**

**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:

**Only for .NET:**

**b. Register Block-Auth** before `var app = builder.Build();`:

**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,
})
```

**PHP · public/index.php · before your router**

```php
$routes = new BlockAuthRoutes(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'), [
    'appUrl' => getenv('APP_URL'),
]);
```

**Python (Flask) · Below app = Flask(...)**

```python
routes = BlockAuthRoutes(
    os.environ["BLOCKAUTH_API_KEY"],
    os.environ["BLOCKAUTH_API_SECRET"],
    app_url=os.environ["APP_URL"],
)
```

**Python (FastAPI) · Below app = FastAPI()**

```python
routes = BlockAuthRoutes(
    os.environ["BLOCKAUTH_API_KEY"],
    os.environ["BLOCKAUTH_API_SECRET"],
    app_url=os.environ["APP_URL"],
)
```

**.NET · Program.cs · before builder.Build()**

```csharp
builder.Services.AddBlockAuth(options =>
{
    options.ApiKey = builder.Configuration["BLOCKAUTH_API_KEY"]!;
    options.ApiSecret = builder.Configuration["BLOCKAUTH_API_SECRET"]!;
    options.AppUrl = builder.Configuration["APP_URL"];
});
builder.Services.AddAuthorization();
```

**Only for Node.js:**

**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).

**Only for PHP:**

**Where to put it:** in `public/index.php`, before your router. If your app reads `SESSION_SECRET` from a configuration file (for example, a `config.php` that returns an array), add `BLOCKAUTH_API_KEY`, `BLOCKAUTH_API_SECRET` and `APP_URL` there too, and in the block change each `getenv(…)` to your configuration value.

If `getenv` returns `false`, the variables aren’t reaching PHP: load the `.env` before this block (for example, with `vlucas/phpdotenv`) or define them in your web server or container.

**Only for Python (Flask), Python (FastAPI):**

**Only for Python (Flask):**

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

**Only for Python (FastAPI):**

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

- **That line is inside a function**, like `def create_app()` or `def create_app(config)`: put the block inside the function, also below it. If you leave it outside, importing the file without the variables (from a test, for example) fails with `Set app_url or allowed_origins`. If your tests create the app with their own configuration, give them test values too, like `app_url="http://testserver"`, or they fail with that same error.
- **Your app reads `SESSION_SECRET` from a configuration file** (a `config.py`, a `Settings` class, Flask’s `app.config`…): add `BLOCKAUTH_API_KEY`, `BLOCKAUTH_API_SECRET` and `APP_URL` there too, and in the block change each `os.environ[…]` to your configuration value (for example, `config.blockauth_api_key`). The block still goes below the app line, and you no longer need the `import os` from step a.

**Only for Python (Flask):**

If you see `KeyError: 'BLOCKAUTH_API_KEY'` or `Set app_url or allowed_origins` on startup, the variables aren’t reaching your server: `flask run` only loads the `.env` when `python-dotenv` is installed; with `python app.py` or gunicorn, call `load_dotenv()` first or start with `uv run --env-file .env …`.

**Only for Python (FastAPI):**

If you see `KeyError: 'BLOCKAUTH_API_KEY'` or `Set app_url or allowed_origins` on startup, the variables aren’t reaching your server: start uvicorn with `--env-file .env` (needs `python-dotenv` installed) or, with uv, `uv run --env-file .env uvicorn …`; you can also load it in your configuration module or export them before starting. If uvicorn answers `No module named 'dotenv'`, install `python-dotenv` or use `uv run --env-file`.

**Only for Node.js:**

**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())
```

**Only for Node.js, PHP, Python (Flask), Python (FastAPI):**

**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:

**Only for .NET:**

**c. Mount it** after `var app = builder.Build();`:

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

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

**PHP · Right after · before your router**

```php
if ($routes->handle()) {
    exit;
}
```

**Python (Flask) · After app = Flask(...) · or inside create\_app()**

```python
app.register_blueprint(blockauth_blueprint(routes))
```

**Python (FastAPI) · After app = FastAPI() · next to your routers**

```python
app.include_router(blockauth_router(routes))
```

**.NET · Program.cs · after builder.Build()**

```csharp
app.UseAuthentication();
app.UseAuthorization();
app.MapBlockAuth();
```

**Only for Node.js:**

**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.

**Only for Python (Flask):**

**Put it before any catch-all route** (like `@app.route("/<path:path>")`) **and before serving your frontend**. 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.

**Only for Python (FastAPI):**

**Put it before any catch-all route** (like `/api/{path:path}`) **and before `app.mount("/", ...)`** if FastAPI serves your frontend. 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)`.

**Checklist for PHP:**

- **`handle()` goes at the top**, before your router and any output.
- **You load the `.env`**: `getenv()` doesn’t read it by itself. Use your web server or `vlucas/phpdotenv`.
- **Laravel or Symfony?** Call `$routes->dispatch(...)` from a route, pass your session with the `session` option and exclude `/auth/blockauth/*` from CSRF.

**Checklist for Python (Flask):**

- **`app.secret_key` is set**: Flask’s session needs it.
- **`register_blueprint` goes after you create `app`**, or inside `create_app()`.
- **You load the `.env`**: `flask run` with `python-dotenv` installed; with `python app.py` or gunicorn, `load_dotenv()` on startup or `uv run --env-file .env …`.
- **Using `CSRFProtect`?** Exempt the blueprint with `csrf.exempt(...)`.

**Checklist for Python (FastAPI):**

- **You have `SessionMiddleware`**, once: `app.add_middleware(SessionMiddleware, secret_key=...)`.
- **`include_router` goes after you create `app`**.
- **You load the `.env`**: `uvicorn main:app --env-file .env` (with `python-dotenv` installed) or `uv run --env-file .env uvicorn main:app`.

**Checklist for .NET:**

- **`AddBlockAuth` goes before `builder.Build()`**.
- **`UseAuthentication()` and `UseAuthorization()` go before `MapBlockAuth()`**, without repeating them.
- **You don’t need `AddSession`**: it uses its own cookie and leaves your authentication alone.

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).

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

Any server, in any language, can do it with plain HTTP. Send the **SHA-256 hash (hex)** of your `apiSecret`, never the secret itself.

The examples use the `AuthCodeClient` of each Block-Auth client library; in Node.js they call the API with `fetch`. Install it where your backend’s `package.json`, `composer.json`, `requirements.txt` or `.csproj` is:

**Node.js · Terminal · only if your server doesn’t have them yet**

```bash
npm install express express-session
```

**PHP · Terminal · next to your backend composer.json**

```bash
composer require blockauth/sdk
```

**Python · Terminal · with your backend environment active**

```bash
pip install blockauth-sdk flask
```

**.NET · Terminal · next to your backend .csproj**

```bash
dotnet add package BlockAuth.Sdk
```

In `POST /code`, redeem the code the widget sends you:

**Redeem the code · Terminal · to try it**

```bash
curl -X POST https://wss.block-auth.io/api/auth/token \
  -H 'Content-Type: application/json' \
  -d '{
    "apiKey": "your_api_key",
    "apiSecret": "sha256_hex_of_your_api_secret",
    "code": "code_from_the_widget",
    "codeVerifier": "code_verifier_from_the_widget",
    "redirectUri": "redirect_uri_from_the_widget"
  }'
```

> **Placeholders in this code:**
>
> - Replace the `sha256_…` value with the SHA-256 hash (hex) of your API Secret. Compute it on your computer, never on a web page.
> - 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 the `…_from_the_widget` values with the ones the widget sends to your `/code` route.

Every response is `{ "success": true, "message": … }`; for `/api/auth/token`, `message` holds `address`, `did` and `roles`. To verify a webhook, compute `v1=` + HMAC-SHA256 of `timestamp.body` (the `X-BlockAuth-Timestamp` header, a dot and the raw body), keyed with the SHA-256 hash of your `apiSecret`, and compare it with `X-BlockAuth-Signature`. All the parameters and errors are in [User login](/api-user-login.md).

Then add these routes under `/auth/blockauth`, or under your `authEndpoint` if you changed it in [Configure the widget](/sdk-integration-spa-frontend.md#config-options). The examples are a complete server. **If you already have a server**, copy only the Block-Auth client (the start of each example) and the three routes: you already have your session and your server start-up. The session must cover `/auth/blockauth`, and in Node.js the webhook route (below) must come before a global `express.json()`:

| Route          | Receives                              | Responds                                                   |
| -------------- | ------------------------------------- | ---------------------------------------------------------- |
| `POST /code`   | `{ code, codeVerifier, redirectUri }` | `{ address, did, roles }` and sets your session cookie     |
| `GET /me`      | —                                     | `{ address, did, roles }`, or `401` if there is no session |
| `POST /logout` | —                                     | `200` and clears your session                              |

> **Note:** Two things the example takes for granted, and that aren’t green because your app usually has them already. Check that you have them:
>
> - **Your router**: the example routes its own way (in PHP, with `if ($route === …)`). If your app already has a router, add the routes to it.
> - **The session open before these routes**: `/code` keeps the user in the session and `/me` reads it. If your app opens the session only when it needs it, open it before these routes too (in PHP, `session_start()`).

**Node.js · server.js · or where you create app = express()**

```javascript
import crypto from 'node:crypto'
import express from 'express'
import session from 'express-session'

const API = 'https://wss.block-auth.io/api'
const { APP_URL, BLOCKAUTH_API_KEY, BLOCKAUTH_API_SECRET, SESSION_SECRET } = process.env
const API_SECRET_HASH = crypto.createHash('sha256').update(BLOCKAUTH_API_SECRET).digest('hex')

export async function blockauth(path, body) {
  const res = await fetch(`${API}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ apiKey: BLOCKAUTH_API_KEY, apiSecret: API_SECRET_HASH, ...body }),
    signal: AbortSignal.timeout(10000),
  })
  const payload = await res.json().catch(() => ({}))
  if (!res.ok || !payload.success) throw new Error(payload.message || `Block-Auth ${res.status}`)
  return payload.message
}

const sessionUser = (user) => ({
  address: user.address,
  did: user.did,
  roles: user.roles,
  expiresAt: Date.parse(`${user.signedExpiredAt.replace(' ', 'T')}Z`),
})

export const currentUser = (req) => {
  const user = req.session.user
  if (user && Date.now() < user.expiresAt) return user
  delete req.session.user
  return null
}

const isOwnUrl = (value) => {
  try {
    return new URL(value).origin === new URL(APP_URL).origin
  } catch {
    return false
  }
}

export const app = express()

app.use(
  session({
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, sameSite: 'lax', secure: APP_URL.startsWith('https') },
  }),
)

app.post('/auth/blockauth/code', express.json(), async (req, res) => {
  const { code, codeVerifier, redirectUri } = req.body ?? {}
  if (typeof code !== 'string' || typeof codeVerifier !== 'string' || !isOwnUrl(redirectUri)) {
    return res.status(400).json({ error: 'invalid_request' })
  }
  try {
    const user = await blockauth('/auth/token', { code, codeVerifier, redirectUri })
    req.session.regenerate((err) => {
      if (err) return res.status(500).end()
      req.session.user = sessionUser(user)
      res.json({ address: user.address, did: user.did, roles: user.roles })
    })
  } catch {
    res.status(502).json({ error: 'blockauth_error' })
  }
})

app.get('/auth/blockauth/me', (req, res) => {
  const user = currentUser(req)
  if (!user) return res.status(401).json({ error: 'unauthenticated' })
  res.json({ address: user.address, did: user.did, roles: user.roles })
})

app.post('/auth/blockauth/logout', async (req, res) => {
  const user = req.session.user
  if (user) await blockauth('/auth/signout', { address: user.address }).catch(() => {})
  req.session.destroy(() => res.json({ ok: true }))
})

app.listen(4000)
```

**PHP · public/index.php · at the top, before your router**

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use BlockAuth\AuthCodeClient;
use BlockAuth\Exceptions\BlockAuthException;

$appUrl = getenv('APP_URL');

session_start([
    'cookie_httponly' => true,
    'cookie_samesite' => 'Lax',
    'cookie_secure' => str_starts_with($appUrl, 'https'),
]);

$blockauth = new AuthCodeClient(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'));

function json(int $status, array $body): void
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($body);
    exit;
}

function currentUser(): ?array
{
    $user = $_SESSION['user'] ?? null;
    if ($user && time() < $user['expires_at']) {
        return $user;
    }
    unset($_SESSION['user']);
    return null;
}

function isOwnUrl(string $value, string $appUrl): bool
{
    $origin = fn ($url) => parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST)
        . (parse_url($url, PHP_URL_PORT) ? ':' . parse_url($url, PHP_URL_PORT) : '');
    return filter_var($value, FILTER_VALIDATE_URL) !== false && $origin($value) === $origin($appUrl);
}

$route = $_SERVER['REQUEST_METHOD'] . ' ' . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if ($route === 'POST /auth/blockauth/code') {
    $body = json_decode(file_get_contents('php://input'), true) ?: [];
    $code = $body['code'] ?? null;
    $verifier = $body['codeVerifier'] ?? null;
    $redirectUri = $body['redirectUri'] ?? '';
    if (!is_string($code) || !is_string($verifier) || !isOwnUrl($redirectUri, $appUrl)) {
        json(400, ['error' => 'invalid_request']);
    }
    try {
        $user = $blockauth->exchangeCode($code, $redirectUri, $verifier);
    } catch (BlockAuthException $e) {
        json(502, ['error' => 'blockauth_error']);
    }
    session_regenerate_id(true);
    $_SESSION['user'] = [
        'address' => $user['address'],
        'did' => $user['did'],
        'roles' => $user['roles'],
        'expires_at' => strtotime($user['signedExpiredAt'] . ' UTC'),
    ];
    json(200, ['address' => $user['address'], 'did' => $user['did'], 'roles' => $user['roles']]);
}

if ($route === 'GET /auth/blockauth/me') {
    $user = currentUser();
    if (!$user) {
        json(401, ['error' => 'unauthenticated']);
    }
    json(200, ['address' => $user['address'], 'did' => $user['did'], 'roles' => $user['roles']]);
}

if ($route === 'POST /auth/blockauth/logout') {
    $user = $_SESSION['user'] ?? null;
    if ($user) {
        try {
            $blockauth->signOut($user['address']);
        } catch (BlockAuthException $e) {
        }
    }
    session_destroy();
    json(200, ['ok' => true]);
}
```

**Python · app.py · or where you create app = Flask(...)**

```python
import os
from datetime import datetime, timezone
from urllib.parse import urlsplit

from flask import Flask, jsonify, request, session
from blockauth_sdk import AuthCodeClient, BlockAuthError

APP_URL = os.environ["APP_URL"]

app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]
app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax", SESSION_COOKIE_SECURE=APP_URL.startswith("https"))

blockauth = AuthCodeClient(os.environ["BLOCKAUTH_API_KEY"], os.environ["BLOCKAUTH_API_SECRET"])


def session_user(user):
    expires_at = datetime.strptime(user["signedExpiredAt"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
    return {"address": user["address"], "did": user["did"], "roles": user["roles"], "expires_at": expires_at.timestamp()}


def current_user():
    user = session.get("user")
    if user and datetime.now(timezone.utc).timestamp() < user["expires_at"]:
        return user
    session.pop("user", None)
    return None


def is_own_url(value):
    if not isinstance(value, str):
        return False
    url, app_url = urlsplit(value), urlsplit(APP_URL)
    return (url.scheme, url.netloc) == (app_url.scheme, app_url.netloc)


@app.post("/auth/blockauth/code")
def redeem_code():
    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:
        user = blockauth.exchange_code(code, redirect_uri, code_verifier=verifier)
    except BlockAuthError:
        return jsonify(error="blockauth_error"), 502
    session.clear()
    session["user"] = session_user(user)
    return jsonify(address=user["address"], did=user["did"], roles=user["roles"])


@app.get("/auth/blockauth/me")
def me():
    user = current_user()
    if not user:
        return jsonify(error="unauthenticated"), 401
    return jsonify(address=user["address"], did=user["did"], roles=user["roles"])


@app.post("/auth/blockauth/logout")
def logout():
    user = session.get("user")
    if user:
        try:
            blockauth.sign_out(user["address"])
        except BlockAuthError:
            pass
    session.clear()
    return jsonify(ok=True)
```

**.NET · Program.cs**

```csharp
using System.Globalization;
using System.Text.Json;
using BlockAuth;
using BlockAuth.Exceptions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = builder.Configuration["APP_URL"]!.StartsWith("https")
        ? CookieSecurePolicy.Always
        : CookieSecurePolicy.SameAsRequest;
});
builder.Services.AddSingleton(new AuthCodeClient(
    builder.Configuration["BLOCKAUTH_API_KEY"]!,
    builder.Configuration["BLOCKAUTH_API_SECRET"]!));

var app = builder.Build();
app.UseSession();

string? CurrentAddress(HttpContext http)
{
    var expiresAt = http.Session.GetString("expires_at");
    var valid = expiresAt is not null && DateTime.ParseExact(expiresAt, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
        DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal) > DateTime.UtcNow;
    if (valid) return http.Session.GetString("address");
    http.Session.Clear();
    return null;
}

var appOrigin = new Uri(builder.Configuration["APP_URL"]!).GetLeftPart(UriPartial.Authority);

bool IsOwnUrl(string? value) =>
    Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.GetLeftPart(UriPartial.Authority) == appOrigin;

app.MapPost("/auth/blockauth/code", async (CodeRequest body, HttpContext http, AuthCodeClient blockauth) =>
{
    if (string.IsNullOrEmpty(body.Code) || string.IsNullOrEmpty(body.CodeVerifier) || !IsOwnUrl(body.RedirectUri))
        return Results.BadRequest(new { error = "invalid_request" });
    try
    {
        var user = await blockauth.ExchangeCodeAsync(body.Code, body.RedirectUri!, body.CodeVerifier);
        http.Session.Clear();
        http.Session.SetString("address", user.Address);
        http.Session.SetString("did", user.Did ?? user.Address);
        http.Session.SetString("roles", user.Roles.GetRawText());
        http.Session.SetString("expires_at", user.SignedExpiredAt);
        return Results.Ok(new { address = user.Address, did = user.Did ?? user.Address, roles = user.Roles });
    }
    catch (BlockAuthException)
    {
        return Results.Json(new { error = "blockauth_error" }, statusCode: 502);
    }
});

app.MapGet("/auth/blockauth/me", (HttpContext http) =>
{
    var address = CurrentAddress(http);
    if (address is null) return Results.Json(new { error = "unauthenticated" }, statusCode: 401);
    var roles = JsonDocument.Parse(http.Session.GetString("roles") ?? "[]").RootElement.Clone();
    return Results.Ok(new { address, did = http.Session.GetString("did") ?? address, roles });
});

app.MapPost("/auth/blockauth/logout", async (HttpContext http, AuthCodeClient blockauth) =>
{
    var address = http.Session.GetString("address");
    if (address is not null)
    {
        try { await blockauth.SignOutAsync(address); } catch (BlockAuthException) { }
    }
    http.Session.Clear();
    return Results.Ok(new { ok = true });
});

app.Run();

record CodeRequest(string? Code, string? CodeVerifier, string? RedirectUri);
```

> **Placeholders in this code:**
>
> - The `app.listen(…)` port is the Backend port from your data. If your server already starts, keep your own `listen`.

> **Note:** The code is valid for 60 seconds and can be redeemed only once. Calling
> `/api/auth/signout` on logout also closes the user's Block-Auth sessions for
> your app on every device.

Your session ends when the user's Block-Auth signature does: `signedExpiredAt`, in UTC with the format `YYYY-MM-DD HH:mm:ss`. That's why the session keeps that moment and every route checks it before trusting the user ([how long a session lasts](/security.md#session)).

Next step: [Connect and try it](/sdk-integration-spa-connect.md)
