Server API
Server-side helpers for session validation, token extraction, runtime configuration, and storage utilities.
Server helpers are exported from both @robojs/auth and @robojs/auth/server. They provide session validation, token extraction, runtime configuration, and storage management.
Session helpers
getServerSession(input?)
Fetches the current session. In local mode, calls the Auth.js handler directly. In proxy mode, fetches the upstream /session endpoint.
function getServerSession(
input?: Request | Headers | [string, string][] | Record<string, string> | null
): Promise<Session | null>function getServerSession(
input?: Request | Headers | [string, string][] | Record<string, string> | null
): Promise<Session | null>| Input type | Description |
|---|---|
Request | Extracts cookies from the request |
Headers | Uses headers directly |
Record<string, string> | Plain header key-value pairs |
null / omitted | Empty headers (returns null) |
import { getServerSession } from '@robojs/auth'
import type { RoboRequest, RoboReply } from '@robojs/server'
export default async (request: RoboRequest, reply: RoboReply) => {
const session = await getServerSession(request)
if (!session) return reply.code(401).send({ error: 'Unauthorized' })
return { user: session.user }
}import { getServerSession } from '@robojs/auth'
export default async (request, reply) => {
const session = await getServerSession(request)
if (!session) return reply.code(401).send({ error: 'Unauthorized' })
return { user: session.user }
}Throws Error if auth runtime has not been configured (plugin not started).
getToken(input?, options?)
Extracts and optionally decodes the Auth.js session token. Behavior depends on session strategy and raw option.
function getToken(
input?: Request | Headers | [string, string][] | Record<string, string> | null,
options?: { raw?: boolean }
): Promise<JWT | string | Session | null>function getToken(
input?: Request | Headers | [string, string][] | Record<string, string> | null,
options?: { raw?: boolean }
): Promise<JWT | string | Session | null>| Strategy | raw: false (default) | raw: true |
|---|---|---|
| JWT | Decoded JWT payload | Raw cookie string |
| Database | Session object (via getServerSession) | Raw cookie string |
import { getToken } from '@robojs/auth'
const token = await getToken(request)
console.log(token?.sub, token?.email)
// Raw cookie value
const raw = await getToken(request, { raw: true })import { getToken } from '@robojs/auth'
const token = await getToken(request)
console.log(token?.sub, token?.email)
// Raw cookie value
const raw = await getToken(request, { raw: true })Throws Error if JWT decoding is attempted without a configured secret.
Runtime configuration
configureAuthRuntime(config, options)
Initializes the auth handler for local mode. Called automatically by the plugin during startup. Only use this for custom setups outside the normal plugin lifecycle.
function configureAuthRuntime(config: AuthConfig, options: ConfigureAuthRuntimeOptions): voidfunction configureAuthRuntime(config, options): voidProp
Type
configureAuthProxyRuntime(options)
Configures upstream proxy mode. Called automatically when upstream is configured.
function configureAuthProxyRuntime(options: ConfigureAuthProxyRuntimeOptions): voidfunction configureAuthProxyRuntime(options): voidProp
Type
createAuthRequestHandler(config)
Creates a Robo-compatible request handler from an Auth.js config. Useful for custom HTTP routers or activity setups.
function createAuthRequestHandler(config: AuthConfig): (req: RoboRequest, res: RoboReply) => Promise<Response>function createAuthRequestHandler(config): (req, res) => Promise<Response>Configuration and validation
normalizeAuthOptions(options)
Runs raw plugin config through Zod validation and applies defaults. Returns a NormalizedAuthPluginOptions object.
import { normalizeAuthOptions } from '@robojs/auth'
const normalized = normalizeAuthOptions(rawConfig)import { normalizeAuthOptions } from '@robojs/auth'
const normalized = normalizeAuthOptions(rawConfig)authPluginOptionsSchema
Zod schema for validating AuthPluginOptions. Strict mode — rejects unknown fields.
import { authPluginOptionsSchema } from '@robojs/auth'
const result = authPluginOptionsSchema.safeParse(config)
if (!result.success) console.error(result.error)import { authPluginOptionsSchema } from '@robojs/auth'
const result = authPluginOptionsSchema.safeParse(config)
if (!result.success) console.error(result.error)Storage helpers
listUsers(page?)
Paginate Flashcore-stored users. Default page size: 500.
function listUsers(page?: number): Promise<{
users: AdapterUser[]
page: number
pageCount: number
total: number
}>function listUsers(page?: number): Promise<{
users: AdapterUser[]
page: number
pageCount: number
total: number
}>listUserIds(page?)
Lighter variant — returns IDs only.
function listUserIds(page?: number): Promise<{
ids: string[]
page: number
pageCount: number
total: number
}>function listUserIds(page?: number): Promise<{
ids: string[]
page: number
pageCount: number
total: number
}>listPrismaUsers(client, options?)
Paginate Prisma-stored users with custom filtering and ordering.
function listPrismaUsers(client: PrismaClientLike, options?: {
page?: number
pageSize?: number
orderBy?: unknown
where?: unknown
}): Promise<{
users: AdapterUser[]
page: number
pageCount: number
total: number
}>function listPrismaUsers(client: PrismaClientLike, options?: {
page?: number
pageSize?: number
orderBy?: unknown
where?: unknown
}): Promise<{
users: AdapterUser[]
page: number
pageCount: number
total: number
}>listPrismaUserIds(client, options?)
Same as above but returns IDs only.
import { listUsers, listPrismaUsers } from '@robojs/auth'
// Flashcore
const { users, total } = await listUsers(0)
// Prisma
const { users } = await listPrismaUsers(prisma, { page: 0, pageSize: 100 })import { listUsers, listPrismaUsers } from '@robojs/auth'
// Flashcore
const { users, total } = await listUsers(0)
// Prisma
const { users } = await listPrismaUsers(prisma, { page: 0, pageSize: 100 })Utilities
getRequestPayload(request)
Parses and caches request body. Supports JSON and form data with mutation helpers. See email and password for detailed usage.
function getRequestPayload(request: RoboRequest): Promise<RequestPayloadHandle>function getRequestPayload(request): Promise<RequestPayloadHandle>Returns a RequestPayloadHandle with these methods:
get<T>()— Retrieve typed payload objectreplace(data)— Replace entire payloadassign(partial)— Merge partial datasource— Payload origin:'json','form', or'empty'
assertPasswordAdapter(adapter)
Validates that an adapter implements all PasswordAdapter methods. Throws with a descriptive message listing missing methods.
import { assertPasswordAdapter } from '@robojs/auth'
assertPasswordAdapter(myAdapter) // throws if methods missingimport { assertPasswordAdapter } from '@robojs/auth'
assertPasswordAdapter(myAdapter) // throws if methods missingauthLogger
Forked logger instance with namespace 'auth'. Import for consistent logging:
import { authLogger } from '@robojs/auth'
authLogger.info('Custom auth logic executed')import { authLogger } from '@robojs/auth'
authLogger.info('Custom auth logic executed')Constants
AUTH_ROUTES
Array of route definitions the plugin registers. Useful for documentation or custom routing.
DEFAULT_BASE_PATH
Literal '/api/auth'.
Exported types
Key server-side types available from @robojs/auth:
AuthPluginOptions— Plugin config shapeConfigureAuthRuntimeOptions/ConfigureAuthProxyRuntimeOptions— Runtime setupPasswordAdapter/PasswordRecord— Adapter contractsPrismaAdapterOptions/PrismaClientLike— Prisma typesRequestPayloadHandle— Parsed request body handle
Re-exported Auth.js types:
Session,JWT,AuthConfig,Adapter,AdapterUser,AdapterSession,AdapterAccount,VerificationToken
