Skip to content

Write Data

Overview


At the core, prefsdb.com can write and store anything from simple key/value pairs, to large data blobs, or serialize and deserialize entire objects.

All functions take the data and an optional options object.

Syntax:

         .write( data, [options])

         .setItem( key, value, [options])

         .putObject( file, [options])

[Promise promise = ] .write( data , [options] )

Use .write() (or .setItem()) to store any value: text, a number, or an object. A single value can be up to 1 MB; for anything bigger, upload a file with .putObject(). A larger value gets an error (VALUE_TOO_LARGE) instead of being stored. Key names can be up to 240 characters, and can contain any characters, emoji included. They match regardless of upper or lower case: Theme and theme are the same key.

.putObject() uploads a file, and .getObject() downloads it again (see below).

Parameters

parameter type description
data text | number | object Data to be stored, up to 1 MB (4 MB on Plus, 8 MB on Pro). It's stored exactly as given, including characters like +, % and &, any language, and emoji. Objects are stored as JSON and come back as objects when read.
options { } Optional object containing overrides, such as set your own request timeout, onsuccess and onerror handlers. Every function returns a Promise; the handlers are an alternative to awaiting it. See Options.

.write()

Stores a value under the current key, replacing what was there, or adds it to the current list. The value is sent in the request body, so it doesn't show up in web addresses or server logs.

.setItem()

Convenience alias method for familiarity with local Storage in a browser.

Usage

.setItem("theme", "dark")

It is equivalent to

.key("theme").write("dark")

.putObject()

Uploads a file (a File from an <input type="file">, or any Blob). The file is encrypted at rest; the response's file field is the id you pass to .getObject() or .deleteObject() later.

Usage:

[Promise promise = ] .putObject(file [, options])

To store an object as data rather than as a file, use .write(object) or .setItem("myObj", object).

Examples


Key/value Example

First, include the PrefsDB JavaScript library in your project:

<script src="https://prefsdb.com/prefsdb.v1.min.js"></script>

Then get your API key (see Getting started).

const db = await PrefsDB.getkey("my-app", ["secret1", "secret2"], { email: "you@example.com" });

IMPORTANT!

Make sure to use the same secrets in the seed array. If you change seed parameters or even reorder them within an array - it will result in a new key being generated and existing data under the old key may be lost.

You are now ready to store and retrieve data.

For instance, to store a value identified by a key named foobar

await db.key("foobar").write({ theme: "light", score: 200, level: 3 });
# The value is the request body; the key goes in the address, ending in "=".
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" -H "Content-Type: text/plain" \
  --data-binary '{"theme":"light","score":200,"level":3}' "https://prefsdb.com/api/v1/write/?foobar="

or, one key per value:

await db.key("theme").write("light");
await db.key("score").write(200);
await db.key("level").write(3);
# Several key=value pairs in one request are written together.
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" -G https://prefsdb.com/api/v1/write/ \
  -d theme=light -d score=200 -d level=3

Over plain HTTP

Short values can go in the address as key=value, as above, which also lets you write several keys at once. Send anything longer, or anything you'd rather keep out of server logs, as the request body (key= in the address, the value as the body), as the JavaScript client does.

Object serialization

The sample code below serializes (saves) an object instance as "myObj".

const obj = { field1: "A", field2: "B" };

await db.key("myObj").write(obj);
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" -H "Content-Type: text/plain" \
  --data-binary '{"field1":"A","field2":"B"}' "https://prefsdb.com/api/v1/write/?myObj="

Lists

Lists are un-ordered collections of data. Prefsdb.com makes it easy and effortless to collect data in a list.

await db.list("signups").add("jane.doe@somewhere.com");
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" -G https://prefsdb.com/api/v1/write/ \
  -d list=signups --data-urlencode "*=jane.doe@somewhere.com"

Files

const file = document.querySelector("input[type=file]").files[0];

const res = await db.domain("uploads").putObject(file);
console.log("file id:", res.file);   // keep it to download or delete the file later
# Needs a getkey call from the last 60 seconds (see Getting started).
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" \
  -F "file=@report.pdf" -F domain=uploads https://prefsdb.com/api/v1/putobject/

Storage space

Each key can store files up to a limit set by its plan. getkey(), every upload and every file delete report how much of it is used, so your app can warn its users before uploads start failing. You decide when to warn and what to say.

db.onStorage(({ used, max, ratio }) => {
    if (ratio !== null && ratio >= 0.8) {
        showNotice("Your storage is almost full. Delete some files, or upgrade for more space.");
    }
});
# getkey, putobject and deleteobject responses all include:
#   "storage": { "used": 41943040, "max": 52428800, "plan": "free" }
# max is null when the plan has no limit.

Users can free up space by deleting files, or upgrade from the page their review link opens (db.reviewUrl()).

Response

Generally a response will contain a an indicator of how many fields were changed. Field updated show how many values were updated - should be 1 or 2. 2 is not an error, it is a correct number indicating internal update path (has to do with internal key constraints being triggered).

{
    "success": true,
    "status": "success",
    "updated": 1,
    "version": 41,
    "ts": "2026-03-26 21:16:11"
}

version (when one key or map entry was written) is the value's new version. Pass it back as { ifVersion } to change the value again only if nobody else has in the meantime: see Several Devices.

When no data was written, either the data has not changed or attempt was made to write an empty value.

{
    "success": true,
    "status": "success",
    "updated": 0,
    "message": "No data written or value not changed.",
    "ts": "2026-03-26 21:14:07"
}

Organizing stored data.

Any piece of data can be additionally categorized and stored under a named project, domain, or subdomain.

const data = "base64abcd...";

await db.ttl(10)                // store for 10 days only
        .project("my-project")  // grouping
        .domain("test-domain")  // grouping
        .key("JohnDoe")         // additional (optional) identifier for the data
        .write(data);
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" -H "Content-Type: text/plain" \
  --data-binary "base64abcd..." \
  "https://prefsdb.com/api/v1/write/?JohnDoe=&project=my-project&domain=test-domain&ttl=10"

Coming soon

A Java client is planned. Until it's available, call the HTTP API directly from any HTTP client — see the cURL tab.

Coming soon

A Python client is planned. Until it's available, call the HTTP API directly (e.g. with requests) — see the cURL tab.


The piece of data saved above can be retrieved using the sample code below.

const incoming = await db.project("my-project")
    .domain("test-domain")
    .key("JohnDoe")
    .read();

if (incoming.success) {
    const mydata = incoming.value;
}
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" -G https://prefsdb.com/api/v1/read/ \
  -d "JohnDoe=" -d project=my-project -d domain=test-domain

Handling Errors

If the server refuses the write, the Promise resolves with success: false, an error code and a message; it rejects only when the request got no answer at all, for example a timeout. With the throwOnError: true option, a refusal rejects too. See How the JavaScript client reports errors.

A write made while offline resolves with queued: true: it's saved in the browser and sent later, but isn't on the server yet. See Offline and Optimistic Writes.

Write success

A successful write operation will return the following response:

{
    "success": true,
    "status": "success",
    "updated": 1,
    "ts": "2026-03-12 02:15:56"
}

Write failure

A failed operation will have its sucess status set to false and offer more details about the error with error code and an error message.

{
    "success": false,
    "status": "error",
    "ts": "2026-03-12 03:18:28",
    "error": "BAD_REQUEST",
    "message": "Missing API key"
}