{"id":16395,"library":"hyperdb","title":"hyperdb: P2P Indexable Database","description":"Hyperdb is a JavaScript library providing a database layer designed for both peer-to-peer (P2P) and local-only data storage, leveraging the Holepunch (formerly Hypercore Protocol) ecosystem. As of version 6.6.0, it offers a schema-driven approach to defining data structures, collections, and indexes using the `Hyperschema` and `hyperdb/builder` tools. It differentiates itself by allowing developers to choose between a P2P backend (Hyperbee) for distributed, eventually consistent data, or a local, embedded database backend (RocksDB) for high-performance, single-instance storage. The project appears to be actively maintained, aligning with the broader Holepunch initiative, though a strict release cadence isn't published. Key features include declarative schema and index definitions, streaming queries, and both synchronous (`await db.get`) and asynchronous (`db.find().toArray()`) data access patterns.","status":"active","version":"6.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/holepunchto/hyperdb","tags":["javascript"],"install":[{"cmd":"npm install hyperdb","lang":"bash","label":"npm"},{"cmd":"yarn add hyperdb","lang":"bash","label":"yarn"},{"cmd":"pnpm add hyperdb","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for defining database schemas and collections during the build step.","package":"hyperschema","optional":false}],"imports":[{"note":"Primary runtime import for database instantiation. The library uses ESM for its main entry point in recent versions (>=6.x), so `import` is preferred over `require`.","wrong":"const HyperDB = require('hyperdb')","symbol":"HyperDB","correct":"import HyperDB from 'hyperdb'"},{"note":"Used in the database definition build script. While the README shows `require`, it is also available via ESM import. For clarity in builder scripts which might be CommonJS, `require` is also common.","wrong":"const HyperDBBuilder = require('hyperdb/builder')","symbol":"HyperDBBuilder","correct":"import HyperDBBuilder from 'hyperdb/builder'"},{"note":"The generated database definition is an ES module. Node.js requires the `.js` extension for local ES module imports unless a custom module resolution is configured.","wrong":"import def from './spec/hyperdb'","symbol":"definition","correct":"import def from './spec/hyperdb/index.js'"}],"quickstart":{"code":"// This quickstart assumes you have already run a builder script (like the one in the README)\n// to generate your database definition files in './spec/hyperdb/index.js'.\n\nimport HyperDB from 'hyperdb';\nimport def from './spec/hyperdb/index.js'; // The generated database definition\n\nasync function run() {\n  // Choose your engine: .rocks for local-only, .bee for P2P\n  // For this example, we'll use RocksDB locally.\n  // Replace './my-local-db' with a suitable path for your database files.\n  const db = HyperDB.rocks('./my-local-db', def, { writable: true });\n\n  await db.ready(); // Ensure the database is initialized and ready for operations\n\n  // Add some entries\n  console.log('Inserting members...');\n  await db.insert('@example/members', { name: 'Alice', age: 30 });\n  await db.insert('@example/members', { name: 'Bob', age: 25 });\n  await db.insert('@example/members', { name: 'Charlie', age: 30 });\n  await db.flush(); // Commit changes to the database\n\n  console.log('Querying for Alice by name...');\n  const alice = await db.get('@example/members', { name: 'Alice' });\n  console.log('Found Alice:', alice);\n\n  console.log('Querying for members with names starting C or later (via index)...');\n  // The example index 'members-by-name' has a 'mapNameToLowerCase' helper.\n  const olderMembersStream = db.find('@example/members-by-name', { gte: { key: 'c' } });\n  const olderMembers = await olderMembersStream.toArray();\n  console.log('Members with names starting C or later:', olderMembers.map(m => m.name));\n\n  console.log('Getting one specific member by name using findOne...');\n  const bob = await db.findOne('@example/members', { name: 'Bob' });\n  console.log('Found Bob:', bob);\n\n  await db.close(); // Close the database connection to release resources\n  console.log('Database closed.');\n}\n\nrun().catch(console.error);","lang":"javascript","description":"Demonstrates initializing a local Hyperdb instance (using RocksDB), inserting data into a defined collection, querying by exact match and using an index, and properly closing the database. It assumes database schemas and collections have already been defined and built into './spec/hyperdb/index.js'."},"warnings":[{"fix":"Pass `{ autoUpdate: true }` in the options when initializing `Hyperdb.bee()` for automatic synchronization, or call `await db.update()` periodically to manually fetch new data.","message":"When using `Hyperdb.bee` for P2P databases, the `autoUpdate` option defaults to `false`. This means the database will not automatically sync with updates from the underlying Hyperbee. You must manually call `db.update()` or set `autoUpdate: true` during initialization to ensure data consistency.","severity":"gotcha","affected_versions":">=6.0.0"},{"fix":"Always call `await db.flush()` after a series of write operations to ensure changes are written to disk or replicated.","message":"All write operations (e.g., `insert`, `delete`, `update`) are buffered and require an explicit `await db.flush()` call to be committed and persisted to the underlying storage. Forgetting to flush will result in data not being saved.","severity":"gotcha","affected_versions":">=6.0.0"},{"fix":"Ensure a `build.js` (or similar) script is executed to generate the database definition files (e.g., `./spec/hyperdb/index.js`) before attempting to initialize or use `HyperDB` at runtime.","message":"Hyperdb utilizes a mandatory builder step (using `hyperdb/builder` and `hyperschema`) to generate database definitions. Without correctly defined schemas, collections, and indexes, runtime operations will fail with 'collection not found' errors. This introduces a build-time dependency that must be managed.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"For runtime code, use ES module `import HyperDB from 'hyperdb'`. For builder scripts (if kept as CJS), use `const HyperDBBuilder = require('hyperdb/builder')`. If using TypeScript, ensure your `tsconfig.json`'s `module` and `moduleResolution` settings align with your target Node.js environment and how you intend to run the code.","message":"The documentation and examples show a mix of CommonJS (`require`) for builder scripts and ES Modules (`import`) for runtime usage. Mixing these in the same project or misusing them can lead to module resolution errors.","severity":"gotcha","affected_versions":">=6.0.0"},{"fix":"If real-time reflection of changes is required, re-run the query after modifications have been flushed. For P2P scenarios with `autoUpdate: true`, consider using event listeners if the underlying Hyperbee provides them, or implement a polling mechanism with fresh queries.","message":"Queries executed via `db.find()` operate on a snapshot of the database state at the moment the query is initiated. Any inserts or deletes that occur while a query stream is active will not be reflected in that particular query's results.","severity":"gotcha","affected_versions":">=6.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify that your builder script correctly registers the collection using `exampleDB.collections.register()`, runs `HyperDBBuilder.toDisk(dbBuilder)`, and that your runtime code correctly imports the generated definition via `import def from './spec/hyperdb/index.js'`.","cause":"The specified collection or index was not registered in the database definition, or the definition file was not correctly loaded at runtime.","error":"Error: Collection '@example/members' not found"},{"fix":"When initializing, ensure you explicitly set `{ writable: true }` in the options for `Hyperdb.rocks()` or `Hyperdb.bee()` if you intend to perform write operations.","cause":"The Hyperdb instance was initialized with `writable: false` (for `.bee`) or `readOnly: true` (for `.rocks`), preventing write operations.","error":"Error: Cannot insert, database is read-only"},{"fix":"Ensure your runtime files are treated as ES modules (e.g., use `.mjs` extension or `\"type\": \"module\"` in `package.json`) and use `import HyperDB from 'hyperdb'`. If working with the builder, use `import HyperDBBuilder from 'hyperdb/builder'` or `const HyperDBBuilder = require('hyperdb/builder')` depending on your builder script's module type.","cause":"This typically indicates a CommonJS `require` call in an ES module environment, or an incorrect named/default import for a module that exports a default.","error":"TypeError: (0, _hyperdb.default) is not a constructor"},{"fix":"First, run your `build.js` (or equivalent) script to generate the definition files. Second, confirm that the `import def from './spec/hyperdb/index.js'` path in your runtime code correctly points to the location where the definition was generated, relative to the script's execution context.","cause":"The generated database definition file could not be found at the specified path, often because the builder script was not run or produced output elsewhere.","error":"No such file or directory: './spec/hyperdb/index.js'"}],"ecosystem":"npm"}