• Start

Files

Working with files

File pointers, buckets, and putting or getting bytes from SurrealDB.

File values look like ordinary paths, but are prefixed with an f so SurrealDB knows you mean binary storage, not a plain string.

To use files, a bucket must first be defined with the DEFINE BUCKET statement. The easiest way to experiment with file storage is to start with a bucket that holds files in memory.

DEFINE BUCKET my_bucket BACKEND "memory";

Once a bucket has been defined, you can begin calling methods on file pointers such as .put() and .get() (see the file functions reference).

DEFINE BUCKET my_bucket BACKEND "memory";
f"my_bucket:/some_file.txt".put("Some text inside");
f"my_bucket:/some_file.txt".get();
<string>f"my_bucket:/some_file.txt".get();

Output

-------- Query --------

b"536F6D65207465787420696E73696465"

-------- Query --------

'Some text inside'

A combination of files and SurrealDB's encoding functions can be used to set up ad-hoc memory storage. This can be convenient when running an instance that saves data to disk but prefers to keep certain items in memory.

The following example shows how this pattern might be used for temporary storage such as a user's shopping cart during a single session.

# Set the allowlist env var to allow the directory to be accessed
SURREAL_BUCKET_FOLDER_ALLOWLIST="/users/your_user_name" surreal start --allow-experimental files
-- Set up the in-memory backend
DEFINE BUCKET my_bucket BACKEND "file:/users/your_user_name";

-- Convenience functions to save, decode back into
-- SurrealQL type, and delete
DEFINE FUNCTION fn::save_file($file_name: string, $input: any) {
LET $file = type::file("shopping_carts", $file_name);
$file.put(encoding::cbor::encode($input));
};

DEFINE FUNCTION fn::get_file($file_name: string) -> object {
encoding::cbor::decode(type::file("shopping_carts", $file_name).get())
};

DEFINE FUNCTION fn::delete_file($file_name: string) {
type::file("shopping_carts", $file_name).delete();
};

-- Save current shopping cart
fn::save_file("temp_cart_user_24567", {
items: ["shirt1"],
last_updated: time::now()
});

fn::get_file("temp_cart_user_24567");
-- Returns { items: ['shirt1', 'deck_of_cards'], last_updated: d'2025-11-20T01:03:24.141080Z' }

-- User adds item, save over file with newer information
fn::save_file("temp_cart_user_24567", {
items: ["shirt1", "deck_of_cards"],
last_updated: time::now()
});

fn::get_file("temp_cart_user_24567");
-- Returns { items: ['shirt1', 'deck_of_cards'], last_updated: d'2025-11-20T01:06:02.752429Z' }

-- Session is over, delete temp file
fn::delete_file("temp_cart_user_24567");

Was this page helpful?