{"id":17528,"library":"clefbase","title":"Clefbase SDK and CLI","description":"clefbase is a Firebase-style SDK and CLI for building applications with the Cleforyx backend platform. It offers a comprehensive suite of services including a NoSQL database, authentication, file storage, serverless functions, AI capabilities, and hosting. The current stable version is 2.1.6, indicating active development. While a specific release cadence isn't published in the provided documentation, its versioning suggests regular updates. Key differentiators include its all-in-one backend-as-a-service model, providing a unified API for various backend needs, and its direct competitive positioning against Firebase, offering a similar developer experience. The package ships with TypeScript types and supports Node.js environments version 16.0.0 or higher, with peer dependencies on React and ReactDOM for front-end integration. It provides both an SDK for programmatic interaction and a CLI for project initialization and management.","status":"active","version":"2.1.6","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","clefbase","cleforyx","database","auth","storage","hosting","functions","serverless","typescript"],"install":[{"cmd":"npm install clefbase","lang":"bash","label":"npm"},{"cmd":"yarn add clefbase","lang":"bash","label":"yarn"},{"cmd":"pnpm add clefbase","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for front-end integration, likely for specific client-side features or component bindings not shown in the core SDK example.","package":"react","optional":true},{"reason":"Peer dependency for front-end integration, closely tied with 'react'.","package":"react-dom","optional":true}],"imports":[{"note":"Clefbase is primarily an ESM package since v2, requiring ES module import syntax. CommonJS 'require' will not work correctly.","wrong":"const initClefbase = require('clefbase').initClefbase;","symbol":"initClefbase","correct":"import { initClefbase } from 'clefbase';"},{"note":"These are named exports for accessing specific Clefbase services after initializing the app. Do not attempt to import them from subpaths or as default exports.","wrong":"import getDatabase from 'clefbase/getDatabase';","symbol":"getDatabase, getAuth, getStorage, getHosting, getFunctions, getAI","correct":"import { getDatabase, getAuth } from 'clefbase';"},{"note":"FieldValue provides helper functions like `increment`, `serverTimestamp`, and `arrayUnion` for atomic updates to database fields. It's a named export from the main package.","wrong":"import FieldValue from 'clefbase/FieldValue';","symbol":"FieldValue","correct":"import { FieldValue } from 'clefbase';"}],"quickstart":{"code":"import { initClefbase, getDatabase, getAuth } from \"clefbase\";\n// Assume clefbase.json exists from 'npx clefbase init'\n// For local development or CI, ensure these are available.\n// In a real application, config would typically be loaded securely.\nimport config from \"./clefbase.json\";\n\n// In a real application, avoid hardcoding sensitive data.\n// Use process.env for API Key and Admin Secret, or a secure configuration management.\n// For demonstration, we'll assume config has necessary values or use fallbacks.\nconst app = initClefbase({\n  projectId: config.projectId ?? process.env.CLEFBASE_PROJECT_ID ?? 'YOUR_PROJECT_ID',\n  apiKey: config.apiKey ?? process.env.CLEFBASE_API_KEY ?? 'YOUR_API_KEY',\n  adminSecret: config.adminSecret ?? process.env.CLEFBASE_ADMIN_SECRET ?? '' // Optional, for admin functions\n});\n\nconst db = getDatabase(app);\nconst auth = getAuth(app);\n\nasync function runExample() {\n  console.log(\"Initializing Clefbase application...\");\n\n  // Example: Add a new document\n  const newPost = await db.collection(\"demoPosts\").add({\n    title: \"My First Clefbase Post\",\n    content: \"This is a demonstration of adding a document to Clefbase.\",\n    authorId: \"user-123\",\n    published: true,\n    createdAt: new Date().toISOString()\n  });\n  console.log(`Added post with ID: ${newPost.id}`);\n\n  // Example: Get the document back\n  const fetchedPost = await db.collection(\"demoPosts\").doc(newPost.id).get();\n  console.log(\"Fetched post title:\", fetchedPost?.title);\n\n  // Example: Basic query for published posts\n  const publishedPosts = await db.collection(\"demoPosts\")\n    .where({ published: true })\n    .getDocs();\n  console.log(`Found ${publishedPosts.length} published posts.`);\n\n  // Example: Sign up a dummy user (handle existing user gracefully for repeated runs)\n  try {\n    const { user } = await auth.signUp(\"example@clefbase.com\", \"securePassword123\", {\n      displayName: \"Demo User\",\n    });\n    console.log(`Signed up user: ${user.displayName} (ID: ${user.uid})`);\n  } catch (error: any) {\n    if (error.message.includes(\"User already exists\")) {\n      console.log(\"User already exists, attempting to sign in.\");\n      const { user } = await auth.signIn(\"example@clefbase.com\", \"securePassword123\");\n      console.log(`Signed in user: ${user.displayName} (ID: ${user.uid})`);\n    } else {\n      console.error(\"Auth error:\", error.message);\n    }\n  }\n}\n\nrunExample().catch(console.error);","lang":"typescript","description":"Demonstrates initializing Clefbase, adding/getting documents, querying, and user authentication with basic error handling, using environment variable fallbacks for configuration."},"warnings":[{"fix":"Ensure your project is configured for ESM (e.g., 'type: module' in package.json) and use 'import' statements. If stuck with CommonJS, consider transpilation or using a bundler.","message":"Clefbase v2 and later are primarily designed for ES Modules (ESM). Direct usage with CommonJS 'require()' will likely result in 'TypeError: initClefbase is not a function' or 'Cannot find module' errors.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always load your 'adminSecret' securely, preferably from server-side environment variables (e.g., `process.env.CLEFBASE_ADMIN_SECRET`) and ensure it's never exposed in client-side code bundles. Use 'npx clefbase init' to generate a secure configuration.","message":"Services like 'getHosting' and certain database admin operations require an 'adminSecret' in your configuration. Exposing this secret client-side or using an invalid secret will lead to 'Permission denied' errors and severe security vulnerabilities.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always check for `null` when retrieving documents: `const doc = await db.collection('coll').doc('id').get(); if (doc) { /* use doc */ }`.","message":"Database `doc().get()` methods return `null` when a document is not found, rather than throwing an error. Developers expecting an error for non-existent documents might encounter `TypeError: Cannot read properties of null` if they don't perform null checks.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always start by running `npx clefbase init` in your project root and follow the prompts. Ensure `clefbase.json` is correctly structured and contains valid credentials (Project ID, API Key, Admin Secret).","message":"The `npx clefbase init` command is essential for project setup, generating the `clefbase.json` configuration file and `.env.example`. Skipping this step or manually creating an incorrectly formatted `clefbase.json` will lead to SDK initialization failures.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure your project uses ES Modules (`import ... from 'pkg'`) and is configured with `'type': 'module'` in `package.json` for Node.js, or use a bundler that handles ESM correctly.","cause":"Attempting to import `initClefbase` using CommonJS `require()` syntax in an ES Module context, or vice-versa.","error":"TypeError: initClefbase is not a function"},{"fix":"Run `npx clefbase init` to generate a valid `clefbase.json` or ensure that `projectId` and `apiKey` are correctly provided via environment variables or a manually constructed config object.","cause":"The `projectId` or `apiKey` is missing or invalid in the configuration object passed to `initClefbase`.","error":"ClefbaseError: PROJECT_ID_MISSING: Project ID is required for SDK initialization."},{"fix":"Provide the correct `adminSecret` in your Clefbase configuration. Ensure it is loaded securely from environment variables and is never exposed in client-side code.","cause":"Attempting to use an API requiring elevated privileges (e.g., `getHosting`, certain database operations) without a valid `adminSecret` in the configuration.","error":"ClefbaseError: Permission denied (403): Invalid Admin Secret or insufficient permissions for operation."},{"fix":"Always check if the document object is not `null` before attempting to access its properties: `const user = await db.getDoc('users', 'uid-123'); if (user) { console.log(user.id); }`.","cause":"Accessing properties on a document object returned by `db.collection(...).doc(...).get()` without checking if the document exists (i.e., if it's `null`).","error":"TypeError: Cannot read properties of null (reading 'id')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}