Auth
Authentication is built into ApiPlugin. Define an auth block in your config to enable it — omit it to disable completely.
Setup
const roles = ["admin", "editor", "user"] as const;
type Role = (typeof roles)[number];
new ApiPlugin<Role>({
auth: {
roles,
defaultRole: "user",
jwt: {
secret: "your-secret-key-at-least-32-characters",
expiresIn: "7d", // "1h" | "30m" | "7d" | seconds as number
algorithm: "HS256", // "HS256" | "HS512" — default: "HS256"
} satisfies JwtConfig,
session: {
store: "memory", // "memory" (default) or a custom SessionStore instance
maxAge: 86400, // seconds — default: 86400 (24 hours)
checkPeriod: 3600, // expired session cleanup interval in seconds — default: 3600
prefix: "datrix:session:", // session key prefix for memory store — default: "datrix:session:"
} satisfies SessionConfig,
defaultPermission: {
create: ["admin"],
read: true,
update: ["admin", "editor"],
delete: ["admin"],
},
passwordReset: {
tokenExpirySeconds: 3600, // default: 1 hour
onForgotPassword: async (user: AuthenticatedUser<Role>, token) => {
// user contains the full authenticated record (password fields excluded)
// send the token however you like — email, Telegram, SMS, etc.
await myMailer.send({
to: user.email,
subject: "Reset your password",
body: `https://example.com/reset?token=${token}`,
});
},
},
} satisfies AuthConfig<Role>,
});
JWT and session can be enabled simultaneously — responses include both a token and a session cookie.
A user schema with an email field must exist before enabling auth. The plugin creates an authentication table alongside it automatically. Authentication records are created for users inserted through create, createMany, upsert and upsertMany; upserted rows that matched an existing user get none (upsert support is new in 0.2.1). When a user's email changes (an update, or an upsert with email in update), the authentication email is synced.
Endpoints
| Method | Path | Description |
|---|---|---|
POST | /api/auth/register | Create a new user account |
POST | /api/auth/login | Login, receive token / session cookie |
POST | /api/auth/logout | Invalidate session |
GET | /api/auth/me | Get the currently authenticated user |
POST | /api/auth/forgot-password | Request a password reset token |
POST | /api/auth/reset-password | Reset password using the token |
Register
POST /api/auth/register
Content-Type: application/json
{
"email": "[email protected]",
"password": "secret123"
}
{
"data": {
"user": {
"id": 1,
"email": "[email protected]"
},
"token": "eyJ..."
}
}
Login
POST /api/auth/login
Content-Type: application/json
{
"email": "[email protected]",
"password": "secret123"
}
When session is enabled, the response also sets a sessionId cookie (HttpOnly).
Forgot Password
Requires passwordReset.onForgotPassword to be configured — otherwise the endpoint returns 403. Always responds with { data: { success: true } } regardless of whether the email exists (prevents user enumeration).
POST /api/auth/forgot-password
Content-Type: application/json
{
"email": "[email protected]"
}
{
"data": {
"success": true
}
}
Reset Password
Verifies the token and updates the password. The token expires after passwordReset.tokenExpirySeconds seconds (default: 1 hour).
POST /api/auth/reset-password
Content-Type: application/json
{
"token": "a3f9...",
"password": "newSecret123"
}
{
"data": {
"success": true
}
}
Authenticated requests
Pass the JWT token in the Authorization header:
GET /api/products
Authorization: Bearer eyJ...
Or send the session cookie — the browser handles this automatically.
Permissions
Permissions are defined per schema. They control who can call each CRUD action.
defineSchema({
name: "product",
fields: { ... },
permission: {
create: ["admin", "editor"], // role array
read: true, // public
update: ["admin", "editor"],
delete: ["admin"],
} satisfies SchemaPermission<Role>,
} satisfies SchemaDefinition)
Permission values
| Value | Meaning |
|---|---|
true | Public — no authentication required |
false | Blocked for everyone |
["admin", "editor"] | Allowed for these roles only |
async (ctx) => boolean | Dynamic — evaluated per request |
When a schema has no permission and defaultPermission doesn't cover the action: read is allowed for everyone, and create/update/delete require an authenticated user (an anonymous request is rejected, not allowed).
ctx.user shape
ctx.user is the authentication record, not the user record — its id is the auth row's id, not the id your authorId/userId foreign keys point to. The populated user record is available at ctx.user.user:
ctx.user satisfies {
id: number // authentication record id
email: string
role: Role
user: DatrixRecord // the populated user record — compare FKs against ctx.user.user.id
} | undefined
Dynamic permissions
permission: {
update: [
"admin",
async (ctx) => {
const record = await ctx.datrix.findById("post", ctx.id!)
return record?.authorId === ctx.user?.user?.id
},
] satisfies PermissionValue<Role>,
}
Field-level permissions
Restrict read or write access to individual fields:
fields: {
email: {
type: "string",
permission: {
read: ["admin", "editor"], // hidden from other roles
} satisfies FieldPermission<Role>,
},
salary: {
type: "number",
permission: {
write: ["admin"], // only admin can set this
} satisfies FieldPermission<Role>,
},
}
defaultPermission
Applied to schemas that have no permission defined:
auth: {
defaultPermission: {
create: ["admin"],
read: true,
update: ["admin"],
delete: ["admin"],
},
} satisfies AuthConfig<Role>
Configuration reference
auth.jwt
| Option | Type | Default | Description |
|---|---|---|---|
secret | string | — | Required. Min 32 characters. |
expiresIn | string | number | "7d" | Token lifetime. String ("7d") or seconds. |
algorithm | "HS256" | "HS512" | "HS256" | Signing algorithm. |
issuer | string | — | JWT iss claim. |
audience | string | — | JWT aud claim. |
auth.session
| Option | Type | Default | Description |
|---|---|---|---|
store | "memory" | SessionStore | "memory" | Session storage backend. Pass a SessionStore instance for custom backends (Redis, database, etc.). |
maxAge | number | 86400 | Session lifetime in seconds. |
checkPeriod | number | 3600 | Expired session cleanup interval in seconds. |
prefix | string | "datrix:session:" | Session key prefix — only used with the default memory store. |
To use a custom store, implement the SessionStore interface exported from @datrix/api:
import type { SessionStore, SessionData } from "@datrix/api"
class RedisSessionStore implements SessionStore {
async get(id: string): Promise<SessionData | undefined> { ... }
async set(id: string, data: SessionData): Promise<void> { ... }
async delete(id: string): Promise<void> { ... }
async cleanup(): Promise<number> { ... }
async clear(): Promise<void> { ... }
}
// Then pass it to session config:
session: {
store: new RedisSessionStore(redisClient),
}
auth.password
| Option | Type | Default | Description |
|---|---|---|---|
iterations | number | 100000 | PBKDF2 iterations. |
keyLength | number | 64 | Derived key length in bytes. |
minLength | number | 8 | Minimum password length. |
auth.userSchema
| Option | Type | Default | Description |
|---|---|---|---|
name | string | "user" | Schema name for the user model. |
email | string | "email" | Field name used as the login identifier. |
auth.authSchemaName
| Option | Type | Default | Description |
|---|---|---|---|
authSchemaName | string | "authentication" | Name of the internal table that stores hashed passwords and session data alongside the user schema. |
auth.endpoints
Override the default auth route paths or disable registration entirely:
auth: {
endpoints: {
login: "/auth/login", // default
register: "/auth/register", // default
logout: "/auth/logout", // default
me: "/auth/me", // default
forgotPassword: "/auth/forgot-password", // default
resetPassword: "/auth/reset-password", // default
disableRegister: false, // set true to block new registrations
},
}
| Option | Type | Default | Description |
|---|---|---|---|
login | string | "/auth/login" | Login endpoint path. |
register | string | "/auth/register" | Register endpoint path. |
logout | string | "/auth/logout" | Logout endpoint path. |
me | string | "/auth/me" | Current user endpoint path. |
forgotPassword | string | "/auth/forgot-password" | Forgot password endpoint path. |
resetPassword | string | "/auth/reset-password" | Reset password endpoint path. |
disableRegister | boolean | false | Block all new user registrations. |
auth.passwordReset
Password reset is disabled by default. Set onForgotPassword to enable it.
auth: {
passwordReset: {
tokenExpirySeconds: 3600, // default: 1 hour
onForgotPassword: async (user: AuthenticatedUser<Role>, token: string) => {
// user contains the full authenticated record (password fields excluded)
// use token to build your reset link, then notify however you prefer
await myMailer.send({
to: user.email,
subject: "Reset your password",
body: `https://example.com/reset?token=${token}`,
});
},
},
} satisfies AuthConfig<Role>
| Option | Type | Default | Description |
|---|---|---|---|
tokenExpirySeconds | number | 3600 | Reset token lifetime in seconds. |
onForgotPassword | (user: AuthenticatedUser, token: string) => Promise<void> | — | Called after a token is generated. Use it to send an email, Telegram message, or any notification. Required to activate the endpoint. |