Serialization
Turn records into JSON, keep secrets out of responses and logs, and print records in the console.
At a glance
| To | Write |
|---|---|
| send a record as JSON | Response.json(account) |
| read its attributes as JavaScript values | account.attributes() |
| keep an attribute out of JSON | static override hiddenAttributes = ["passwordDigest"] |
show an attribute as [FILTERED] in logs |
static override filterAttributes = [...Model.filterAttributes, "iban"] |
| see a record or a Relation | console.log(account) |
| Setting | Keeps values out of | Default |
|---|---|---|
hiddenAttributes |
toJSON(), so Response.json and JSON.stringify |
nothing |
filterAttributes |
onQuery listeners, error messages, and printed records |
passwords, emails, tokens, keys, and the like |
The Model
The examples use this Model, whose attributes come from its table through the schema active-record schema generates. Your app’s base class holds the settings every Model shares:
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";
export abstract class ApplicationRecord extends Model {
static override schema = schema;
// Left out of toJSON(), so Response.json(record) never sends them:
static override hiddenAttributes = ["passwordDigest"];
// Shown as [FILTERED] in logs, errors, and printed records: the defaults, and an IBAN.
static override filterAttributes = [...Model.filterAttributes, "iban"];
}import { ApplicationRecord } from "./application-record";
export class Account extends ApplicationRecord {
// A Model's list replaces the base class's, so repeat what you still want hidden:
static override hiddenAttributes = [...ApplicationRecord.hiddenAttributes, "apiKey"];
}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 0735d8f7f772
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** accounts — last changed by 0001_create_accounts.sql */
export const accounts = {
id: { type: "string", null: false, generateId: true },
email: { type: "string", null: false },
passwordDigest: "string",
apiKey: "string",
iban: "string",
createdAt: { type: "datetime", null: false },
updatedAt: { type: "datetime", null: false },
} as const;
/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
adapter: d1({ binding: "DB" }),
tables: {
accounts: { attributes: accounts, primaryKey: "id" },
},
models: { Account: "accounts" },
});
declare module "../models/account" {
interface Account extends TableAttributes<typeof accounts, (typeof Account)["attributes"]> {}
}CREATE TABLE accounts (
id TEXT PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
password_digest TEXT,
api_key TEXT,
iban TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);CREATE TABLE accounts (
id UUID PRIMARY KEY,
email TEXT NOT NULL,
password_digest TEXT,
api_key TEXT,
iban TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);Serializing records
toJSON() gives a record’s attributes with dates as ISO strings, and attributes() gives them with JavaScript values:
import { class AccountAccount } from "./models/account";
const const account: Accountaccount = await class AccountAccount.findByOrThrow<typeof Account>(this: typeof Account, conditions: SafeSql | Conditions<Account>): Promise<Account>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const const body: stringbody = var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.JSON.JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.stringify(const account: Accountaccount); // dates as ISO strings, passwordDigest and apiKey left out
const const attributes: Record<string, unknown>attributes = const account: Accountaccount.Model.attributes(): Record<string, unknown>The record's attributes as a plain object of JavaScript values.attributes(); // every attribute, dates as DateAssociations are never included, so a response never loads more than you asked for. Response.json(record) uses toJSON():
import { class AccountAccount } from "./models/account";
export async function function show(request: Request): Promise<Response>show(request: Requestrequest: Request): interface Promise<T>Represents the completion of an asynchronous operationPromise<Response> {
const const email: stringemail = new var URL: new (url: string | URL, base?: string | URL) => URLThe **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)URL(request: Requestrequest.Request.url: stringThe **`url`** read-only property of the Request interface contains the URL of the request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)url).URL.searchParams: URLSearchParamsThe **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)searchParams.URLSearchParams.get(name: string): string | nullThe **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)get("email") ?? "";
const const account: Account | nullaccount = await class AccountAccount.findBy<typeof Account>(this: typeof Account, conditions: SafeSql | Conditions<Account>): Promise<Account | null>The first record matching `conditions` (in no particular order), or null.findBy({ email?: string | readonly string[] | Comparison<string> | undefinedemail });
return const account: Account | nullaccount ? var Response: {
new (body?: BodyInit | null, init?: ResponseInit): Response;
prototype: Response;
error(): Response;
json(data: any, init?: ResponseInit): Response;
redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response.function json(data: any, init?: ResponseInit): ResponseThe **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)json(const account: Accountaccount) : new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response("Not found", { ResponseInit.status?: number | undefinedstatus: 404 });
}Hiding attributes
Name an attribute in static hiddenAttributes on your app’s base class to keep it out of every Model’s toJSON(), as ApplicationRecord does with passwordDigest:
- A Model’s own list replaces the base class’s, so
Accountrepeats it besideapiKey. - By default, nothing is hidden, and each name must match an attribute exactly.
attributes()still returns every attribute, so you can send a hidden one on purpose.- A secure password, with its confirmation, challenge, and digest, and a secure token are left out without being listed.
Filtering attributes
onQuery listeners, error messages, and printed records show a filtered attribute’s values as "[FILTERED]", while the database still gets the real values. Logging shows a listener:
- Which attributes:
static filterAttributes, a list of strings and RegExps, inherited from your app’s base class. By default, it’spassw,email,secret,token,_key,crypt,salt,certificate,otp,ssn,cvv,cvc. Setting it replaces the list;[]filters nothing by name. A secure password, with its confirmation, challenge, and digest, and a secure token are filtered whatever the list says. - Matching: a string matches when the attribute’s snake_case name contains it, in any case:
passwordDigest(password_digest) containspassw, andapiKey(api_key) contains_key. A string can also be written as the attribute is, so"secretAt","secret_at", and"secret"all matchsecretAt. A RegExp matches the attribute or its snake_case name. - Hidden in
QueryEvent.params: the values bound for the attribute in inserts (in a multi-row insert’s JSON, its column in every row), updates,updateAll, conditions, lists and comparisons, and a filtered primary key in a record’sUPDATEandDELETE. - Hidden in errors: a cast error’s value, and a filtered primary key in
RecordNotFound. - Not hidden: a bare value inside an
sqlfragment, which has no attribute (write it ascolumn("token").value(token)to filter it); andtoJSON()andattributes(), which are your data, not logs (Hiding attributes keeps names out oftoJSON()).
Printing records
console.log(account), a failed test, and the console show a record’s class and attributes:
Account {
id: '3b241101-e2bb-4255-8caf-4136c566a962',
email: [FILTERED],
passwordDigest: [FILTERED],
apiKey: [FILTERED],
iban: [FILTERED],
createdAt: 2026-01-15T00:00:00.000Z,
updatedAt: 2026-01-15T00:00:00.000Z
}
- Filtered attributes print as
[FILTERED], without quotes so it can’t be mistaken for a string, and in a distinct color when the terminal shows colors. An attribute with no value still printsnull. - Unsaved changes print the new value and the old one:
'Johnny' (was 'Alice'). Once the record is saved, the flag goes. A changed filtered attribute prints[FILTERED] (changed), and so does a column a partial record never loaded. A new record flags nothing, since all of it is unsaved. - A partial record prints only the columns it loaded, and bytes print as how many there are:
<3 bytes of binary data>. - Hidden attributes still print: they keep values out of
toJSON(), not out of your console. Printing never loads an association.
A Relation prints the SELECT it would send, without sending it, with a filtered attribute’s value in params as [FILTERED]:
Relation<Account> {
sql: 'SELECT * FROM "accounts" WHERE (("email" = ?))',
params: [ [FILTERED] ]
}
Printing can’t wait for the database, so to see the records, await it or call toArray(). A record’s errors print each failure, so a failed save() shows why in the console:
Errors [
{ attribute: 'name', type: 'blank', message: "can't be blank" },
{ attribute: 'email', type: 'too_short', message: 'is too short' }
]