SimpleAuth
SDK

Server SDK

Complete reference for createServerSimpleAuthClient — admin operations and session resolution for your backend.

The server SDK provides admin operations (user management, bans, sessions) and a way to resolve the current user from session cookies in server-rendered pages and API routes.

This module is server-only. It throws an error if imported in a browser environment. Never include @simpleauthjs/core/server in client bundles.

Installation

npm install @simpleauthjs/core

createServerSimpleAuthClient(options?)

import { createServerSimpleAuthClient } from "@simpleauthjs/core/server"

const adminAuth = createServerSimpleAuthClient({
  secretKey: "sa_secret_…",
})

Options

OptionTypeDefaultDescription
secretKeystringprocess.env.SIMPLEAUTH_SECRET_KEYSecret API key (sa_secret_…). Required for admin methods. Can be omitted if you only use currentUser.
baseUrlstring"https://simpleauth.net"API origin (no trailing slash). Falls back to process.env.SIMPLEAUTH_BASE_URL, then the default. Override when calling a local SimpleAuth server (for example http://localhost:3000).
apiKeyTransport"authorization" | "x-api-key""authorization"How the secret key is sent in headers.
credentialsRequestCredentials"include"Fetch credentials mode.
headersRecord<string, string>{}Extra headers merged into every request.
timeoutMsnumberRequest timeout in milliseconds.
fetchtypeof fetchglobalThis.fetchCustom fetch implementation.
onError(error: SimpleAuthError) => voidCalled on every error before throwing.
onRequest(event) => voidRequest tracing hook.
onResponse(event) => voidResponse tracing hook.
debugbooleanfalseLog requests and responses to the console.

You can skip secretKey in the constructor if SIMPLEAUTH_SECRET_KEY is set. The API host defaults to https://simpleauth.net; set SIMPLEAUTH_BASE_URL only when your server should call a local SimpleAuth instance.


Session resolution

currentUser(requestLike, options?)

Resolve the signed-in user from session cookies. This calls GET /api/external/auth/me and forwards the cookies from the incoming request. It does not use the secret key.

Pass the incoming Request object (in Route Handlers), or { headers } (e.g. Next.js headers()), or { cookie: "..." }.

// Next.js Route Handler
export async function GET(request) {
  try {
    const { user } = await adminAuth.currentUser(request)
    return Response.json({ user })
  } catch (error) {
    if (error instanceof SimpleAuthError && error.status === 401) {
      return new Response("Unauthorized", { status: 401 })
    }
    throw error
  }
}
// Next.js Server Component
import { headers } from "next/headers"

export default async function Page() {
  const { user } = await adminAuth.currentUser({ headers: await headers() })
  return <p>Hello, {user.name}</p>
}

Accepted input types:

  • Request — Web Request object (Route Handlers, edge functions).
  • Headers — Web Headers object.
  • { cookie: string } — raw cookie string.
  • { headers: Headers | { cookie?: string } } — object with a headers property.

Returns: { user: { id, email, name, emailVerified, createdAt } }

Throws: SimpleAuthError with status 401 if there is no valid session.


Admin methods

All admin methods require the secret key. They throw an error if the secret key was not provided.

createUser(input, options?)

Create a user from your backend. Same result as register on the client, but uses the admin endpoint.

const { user } = await adminAuth.createUser({
  email: "newuser@example.com",
  password: "tempP@ssword",
  name: "New User",
})

Parameters:

FieldTypeRequired
emailstringYes
passwordstringYes
namestringNo

Returns: { user: { id, email, name, emailVerified, createdAt } }


getUserById(externalUserId, options?)

Get a user by their external user ID. The response includes bannedUntil if the user is currently banned.

const { user } = await adminAuth.getUserById("ext_user_123")
console.log(user.email, user.bannedUntil)

Returns: { user: { id, email, name, emailVerified, createdAt, bannedUntil } }


deleteUserById(externalUserId, options?)

Permanently delete a user and all their sessions.

await adminAuth.deleteUserById("ext_user_123")

Returns: { success: true }


banUser(externalUserId, input, options?)

Ban a user for a specified duration. Banned users cannot log in until the ban expires.

await adminAuth.banUser("ext_user_123", { durationMinutes: 60 })

Parameters:

FieldTypeRequiredDescription
externalUserIdstringYesThe user's external ID (first argument).
durationMinutesnumberYesBan duration in minutes. Must be a positive number.

Returns: { success: true, bannedUntil: string }


unbanUser(externalUserId, options?)

Remove an active ban from a user.

await adminAuth.unbanUser("ext_user_123")

Returns: { success: true }


listUserSessions(externalUserId, options?)

List all active sessions for a user. Returns session metadata only — no session tokens are exposed.

const { sessions } = await adminAuth.listUserSessions("ext_user_123")

for (const session of sessions) {
  console.log(session.id, session.ipAddress, session.createdAt)
}

Returns: { sessions: [{ id, expiresAt, ipAddress, userAgent, createdAt }] }


deleteUserSession(externalUserId, sessionId, options?)

Revoke a specific session for a user, invalidating that login.

await adminAuth.deleteUserSession("ext_user_123", "session_456")

Returns: { success: true }


revokeAllUserSessions(externalUserId, options?)

Revoke all sessions for a user at once. Useful when a user's account is compromised.

const result = await adminAuth.revokeAllUserSessions("ext_user_123")
console.log(result.revokedCount) // number of sessions revoked

Returns: { success: true, revokedCount: number }

On this page