33. User admin API (server-side)

Create, list, change, suspend and delete your app's users from your own server, with the project's secret key.

Everything the console's Users page does is also an API for your backend: /v1/auth/admin/users, and in the SDK eb.auth.admin. It is the counterpart of Supabase's auth.admin: the same names, so code moving from Supabase changes little. The same rules as the console apply: email checks, passwords of 8–72 bytes, bcrypt with cost 12.

Secret key only. The admin API reads and changes every account of the project, so it answers only to the secret key (eb_sk_…, console → Settings → API keys). Use it on a server or in a script — never in a browser, a mobile app or anything you ship to users. Edge functions can't call it (they can't reach your project's API URL); inside an edge function use ctx.db.sql, or ctx.db.asService() where the function must act as the service. Send the key in the apikey header (the SDK does): a key in the URL (?apikey=) is refused, because URLs end up in logs. A public key gets 403 (secret_key_required); the SDK returns that error without sending a request. An end user's access token on the request plays no part: the key alone authorises.

Setup

// server.js — Node 18+, the secret key from the environment
import { createClient } from '@eurobase/sdk'

const eb = createClient({
  url: 'https://your-project.eurobase.app',
  apiKey: process.env.EUROBASE_SECRET_KEY, // eb_sk_… — never in a browser or an app
})

const { data, error, status, code } = await eb.auth.admin.listUsers({ perPage: 20 })

Requires @eurobase/sdk 0.13.0 or later. Admin requests send only the API key, even if the same client has a signed-in user.

Methods

eb.auth.admin.listUsers({ page, perPage, search })      // { users, total }
eb.auth.admin.createUser({ email, password, emailConfirmed, displayName, metadata })
eb.auth.admin.getUserById(id)
eb.auth.admin.updateUserById(id, { email, displayName, metadata, emailConfirmed })
eb.auth.admin.deleteUser(id)                             // data: null
eb.auth.admin.suspendUser(id)
eb.auth.admin.unsuspendUser(id)
eb.auth.admin.setPassword(id, password)                  // { status: 'password_reset' }
eb.auth.admin.signOutUser(id)                            // { status: 'signed_out', refresh_tokens_revoked }

// Every method resolves to { data, error, status?, code? } and never throws.
SDKHTTPRequestSuccess
listUsersGET /query page (from 1), per_page (1–200, default 50), search (part of the email, display name or id), email (exact match)200 { users, total }, newest first
createUserPOST /email; optional password, email_confirmed (default true), display_name, metadata201 user
getUserByIdGET /{id}—200 user
updateUserByIdPATCH /{id}any of email, display_name, metadata (replaces the whole object), email_confirmed200 user
deleteUserDELETE /{id}—204
suspendUserPOST /{id}/suspend—200 user (banned_at set)
unsuspendUserDELETE /{id}/suspend—200 user
setPasswordPOST /{id}/passwordpassword (8–72 bytes)200 { status: "password_reset" }
signOutUserPOST /{id}/signout—200 { status: "signed_out", refresh_tokens_revoked }

Paths are relative to https://your-project.eurobase.app/v1/auth/admin/users. A user looks like this (no password hash or token data, ever):

{
  "id": "6f486f53-2841-4a86-961b-9673dfb2b58d",
  "email": "ana@partner.example",
  "display_name": "Ana Novak",
  "providers": ["email"],
  "metadata": { "company": "Partner GmbH", "plan": "b2b" },
  "banned_at": null,
  "last_sign_in_at": null,
  "email_confirmed_at": "2026-11-20T09:12:44Z",
  "created_at": "2026-11-20T09:12:44Z"
}

The same with curl

The key goes in the apikey header; the API refuses it in the URL.

export EB=https://your-project.eurobase.app/v1/auth/admin/users
export KEY=eb_sk_...   # the secret key

# List (page is 1-based; per_page 1-200, default 50; search matches email, name or id)
curl -s "$EB?page=1&per_page=50&search=partner" -H "apikey: $KEY"

# Create (password optional; email_confirmed defaults to true)
curl -s -X POST "$EB" -H "apikey: $KEY" -H "Content-Type: application/json" \
  -d '{"email":"ana@partner.example","password":"a-long-password","email_confirmed":true,
       "display_name":"Ana Novak","metadata":{"company":"Partner GmbH"}}'

# Get / update / delete
curl -s "$EB/$USER_ID" -H "apikey: $KEY"
curl -s -X PATCH "$EB/$USER_ID" -H "apikey: $KEY" -H "Content-Type: application/json" \
  -d '{"display_name":"Ana N.","metadata":{"company":"Partner GmbH","plan":"gold"}}'
curl -s -X DELETE "$EB/$USER_ID" -H "apikey: $KEY"            # 204

# Suspend / lift the suspension
curl -s -X POST   "$EB/$USER_ID/suspend" -H "apikey: $KEY"
curl -s -X DELETE "$EB/$USER_ID/suspend" -H "apikey: $KEY"

# Set a new password
curl -s -X POST "$EB/$USER_ID/password" -H "apikey: $KEY" -H "Content-Type: application/json" \
  -d '{"password":"another-long-password"}'

# Sign out everywhere (revoke every refresh token)
curl -s -X POST "$EB/$USER_ID/signout" -H "apikey: $KEY"

Errors

Error bodies are { "error": "…", "code": "…" } (code where listed). The SDK returns them as { data: null, error, status, code }.

  • 400 — invalid email, a password outside 8–72 bytes, a display name over 256 characters, metadata over 16 KiB (as JSON), an unreadable body, or an update with no fields.
  • 401 — no API key, or an unknown one.
  • 403 secret_key_required — any key other than the secret key. apikey_header_required — the secret key was sent in the URL instead of the header.
  • 404 — no user with that id (also for an id that isn't a UUID); suspending a user who is already suspended, or lifting a suspension that isn't there.
  • 409 email_exists — another user has that email (create, or changing the email). user_referenced — deleting a user that other rows still point to without ON DELETE CASCADE, for example files they uploaded or your own tables; remove or reassign those first. retention_hold_active — the user is under a retention hold (Legal Team).
  • 413 body_too_large — a request body over 64 KiB.
  • 429 — too many requests, with a Retry-After header (the SDK's retryAfter, in seconds). Two limits apply: your plan's requests per second, like the data API; and, per project, at most 10 calls in 5 seconds that hash a password (createUser with a password, setPassword) — hashing is deliberately slow. Wait and retry.
  • 503 — maintenance, a Team project's database is not reachable (never served from anywhere else), or a delete whose retention-hold check couldn't run; retry.

What suspend, sign-out and delete do — and don't

  • Suspend stops every new sign-in and revokes all the user's refresh tokens. Their data stays.
  • Sign out revokes all refresh tokens (every device) without suspending: the user can sign in again.
  • Set password also revokes all refresh tokens.
  • Delete removes the user, their sign-in methods and tokens, and rows of your tables that reference them with ON DELETE CASCADE. Files in storage are not deleted for you.
  • Access tokens already issued stay valid until they expire, after any of these. Keep Session duration short (Auth settings). Where it matters, ask the server about the user, not only the token: GET /v1/auth/user with their token (the SDK's getUser) fails for a deleted or suspended user, while verifying the token locally (JWKS, or the SDK's verifyAccessToken) checks only the token's signature and expiry. With the secret key, admin.getUserById(id) shows banned_at for a suspended user and 404 for a deleted one.

Audit log

Every change — create, update, delete, suspend, lift, set password, sign out — is written to the project's audit log (console → Compliance), from the console and from the API alike: end_user.created, end_user.updated (the names of the changed fields, not their values), end_user.deleted, end_user.suspended, end_user.unsuspended, end_user.password_set, end_user.signed_out. Calls with the secret key show the actor secret API key and "via": "secret_key". Reads (list, get) aren't logged. Passwords are never logged.

Use cases

1. Accounts for a company's employees, or a partner's customers (B2B)

Two common shapes: B2B seats — a company buys accounts for its employees and you create them, instead of each person signing up; and partner integrations — another platform creates accounts for its customers through your API, and your server creates the Eurobase users behind it.

Decide access with a table your backend fills, not with metadata: keep the company there only as a label. App users can only read their own row of company_members, so they can't move themselves into another company; your server writes it with the secret key, which the is_service_role() policy admits.

-- Which company each account belongs to. Your backend writes it; users only read their own row.
CREATE TABLE company_members (
  user_id    uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
  company_id uuid NOT NULL REFERENCES companies(id),
  role       text NOT NULL DEFAULT 'member'
);
ALTER TABLE company_members ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_membership ON company_members
  FOR SELECT USING (user_id = auth_uid());
-- Your server (secret key) reads and writes every row.
CREATE POLICY server_manages ON company_members
  FOR ALL USING (is_service_role()) WITH CHECK (is_service_role());

-- Example: everyone in a company sees the company's invoices.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY company_invoices ON invoices
  FOR SELECT USING (company_id IN (
    SELECT company_id FROM company_members WHERE user_id = auth_uid()
  ));

Creating an account sends no email. Without a password, each person sets one through the reset link that auth.forgotPassword(email, { emailRedirectTo }) sends (or signs in with a magic link). Those emails count towards your project's email sending (see Rate Limits): 3 per address per 15 minutes, and 60 reset emails an hour per client IP — and since the client IP isn't always told apart today, count that 60 as shared with the reset requests of the rest of your project. A batch of 20 fits; for more than about 50 an hour, spread the invitations out, or use a magic link or your own email with a link to your sign-in page.

// Your backend creates accounts for a company's employees, records the
// membership, and sends each person a link to choose their password.
export async function onboardCompany(company, employees) {
  const results = []
  for (const person of employees) {
    const { data, error, code } = await eb.auth.admin.createUser({
      email: person.email,
      emailConfirmed: true,                  // you vouch for the address
      displayName: person.name,
      metadata: { company: company.name },  // a label for your UI, not for access rules
    })
    if (code === 'email_exists') {
      results.push({ email: person.email, status: 'exists' })
      continue
    }
    if (error) {
      results.push({ email: person.email, status: 'failed', error })
      continue
    }

    // Access comes from this table (see the policies above), written with the secret key.
    await eb.db.from('company_members').insert({ user_id: data.id, company_id: company.id, role: person.role })

    // Creating an account sends no email. Send the "set your password" link:
    const sent = await eb.auth.forgotPassword(person.email, {
      emailRedirectTo: 'https://app.example.com/set-password', // one of your allowed redirect URLs
    })
    results.push({ email: person.email, status: 'created', id: data.id, invited: !sent.error })

    await new Promise((r) => setTimeout(r, 250)) // pace large batches
  }
  return results
}

2. "Delete my account" in an Express server

Verify who is calling from their access token (see Verifying tokens on your server), then delete that user — never an id the client sends.

// DELETE /account — the signed-in user deletes their own account.
import express from 'express'
import { createRemoteJWKSet, jwtVerify } from 'jose'
import { createClient } from '@eurobase/sdk'

const eb = createClient({ url: process.env.EUROBASE_URL, apiKey: process.env.EUROBASE_SECRET_KEY })
const JWKS = createRemoteJWKSet(new URL(process.env.EUROBASE_URL + '/v1/auth/.well-known/jwks.json'))

const app = express()

app.delete('/account', async (req, res) => {
  // 1. Who is calling? Verify their access token; never trust an id from the body.
  const token = (req.headers.authorization || '').replace(/^Bearer /, '')
  let userId
  try {
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: 'eurobase',
      audience: process.env.EUROBASE_PROJECT_ID,
      algorithms: ['ES256'],
    })
    userId = payload.sub
  } catch {
    return res.status(401).json({ error: 'not signed in' })
  }

  // 2. Delete what your tables keep about them that the database won't cascade
  //    (here: their uploaded files, which reference the user).
  //    ... await eb.storage.remove(...) for each of their files ...

  // 3. Delete the account. Their refresh tokens go with it.
  const { error, status, code } = await eb.auth.admin.deleteUser(userId)
  if (status === 404) return res.status(204).end() // already gone
  if (code === 'user_referenced') return res.status(409).json({ error })
  if (error) return res.status(502).json({ error: 'could not delete the account' })
  res.status(204).end()
})

app.listen(3000)

3. An admin dashboard that lists and searches users

Your dashboard's frontend calls your server; your server calls the admin API. search matches part of the email, display name or id.

// GET /admin/users?page=1&q=ana — your own admin dashboard's API.
// Protect this route with your staff login; the secret key stays on the server.
app.get('/admin/users', requireStaff, async (req, res) => {
  const page = Math.max(1, Number(req.query.page) || 1)
  const { data, error } = await eb.auth.admin.listUsers({
    page,
    perPage: 25,
    search: typeof req.query.q === 'string' ? req.query.q : undefined,
  })
  if (error) return res.status(502).json({ error })
  res.json({
    page,
    pages: Math.ceil(data.total / 25),
    users: data.users.map((u) => ({
      id: u.id,
      email: u.email,
      name: u.display_name,
      suspended: u.banned_at !== null,
      confirmed: u.email_confirmed_at !== null,
      lastSignIn: u.last_sign_in_at,
    })),
  })
})

4. Suspending an abusive user and signing them out everywhere

Suspending already revokes their refresh tokens; their current access token works until it expires.

// A moderator bans an abusive user: suspend (no new sign-in, refresh tokens
// revoked) and record why in their metadata.
export async function banUser(userId, reason, moderator) {
  const { data: user, error } = await eb.auth.admin.getUserById(userId)
  if (error) return { error }

  const suspended = await eb.auth.admin.suspendUser(userId)
  if (suspended.error && suspended.status !== 404) return { error: suspended.error } // 404 = already suspended

  await eb.auth.admin.updateUserById(userId, {
    metadata: { ...user.metadata, bannedReason: reason, bannedBy: moderator, bannedAt: new Date().toISOString() },
  })
  return { error: null }
}

// Lifting the ban later:
//   await eb.auth.admin.unsuspendUser(userId)
// Signing someone out everywhere without suspending them (e.g. a lost phone):
//   await eb.auth.admin.signOutUser(userId)

5. A one-off script that imports users from a CSV file

Re-running it is safe: existing emails answer email_exists and are left unchanged. It goes one user at a time and waits when it gets a 429; without passwords the per-project hashing limit doesn't apply, only your plan's request rate. For large imports with existing password hashes or ids, use the console's batch import (Managing End Users) or the CLI's Supabase import instead.

// import-users.mjs — node import-users.mjs users.csv
// CSV columns: email,name,company   (one user per line, header first)
import { readFile } from 'node:fs/promises'
import { createClient } from '@eurobase/sdk'

const eb = createClient({ url: process.env.EUROBASE_URL, apiKey: process.env.EUROBASE_SECRET_KEY })

const [header, ...lines] = (await readFile(process.argv[2], 'utf8')).trim().split(/\r?\n/)
const cols = header.split(',').map((s) => s.trim())

const sleep = (ms) => new Promise((r) => setTimeout(r, ms))

let created = 0, existing = 0, failed = 0
for (const line of lines) {
  const row = Object.fromEntries(line.split(',').map((v, i) => [cols[i], v.trim()]))
  let res
  for (let attempt = 0; attempt < 5; attempt++) {
    res = await eb.auth.admin.createUser({
      email: row.email,
      displayName: row.name,
      metadata: { company: row.company, importedAt: new Date().toISOString() },
    })
    if (res.status !== 429) break
    await sleep((res.retryAfter ?? 5) * 1000) // over the rate limit: wait, then retry
  }
  const { error, code } = res
  if (!error) created++
  else if (code === 'email_exists') existing++ // safe to re-run
  else { failed++; console.error(row.email, error) }
}
console.log({ created, existing, failed })

The simple split(',') doesn't handle quoted fields; use a CSV parser for real files.