# Fenaura documentation: complete text Source: https://docs.fenaura.dev Pages: 68 --- # Introduction URL: https://docs.fenaura.dev/ Section: Getting started # Introduction Fenaura is a backend you talk to. It gives you four things that every app needs: edge functions, a Postgres database, end-user authentication, and file storage, all wired together inside one project. You do not assemble those pieces yourself. You create a project, and the database, the auth system and the storage buckets already belong to it. ## What you get **Fleets (or your own backend).** Run server-side JavaScript in Fenaura's V8 isolate runtime where every route is private by default (`ctx.user`, `ctx.db`, `ctx.redis` injected automatically), **or** keep your own backend in Node, Python, Go, Rust, or any language and connect directly to your project's Postgres and Redis over TLS using the credentials in **Secrets › Platform secrets**. **A Postgres database.** Every project gets its own isolated Postgres database, not a schema inside a shared one. Query it from browsers via `fenaura-sdk` or plain HTTP `fetch`, from Fleets via `ctx.db` / `ctx.sql`, or from any external backend via standard drivers and ORMs (`pg`, Drizzle, Prisma, `psycopg`, `pgx`, `sqlx`). **End-user authentication.** Email and password, twelve OAuth providers, verification codes, password resets, and magic links. Use `fenaura-sdk` with the domain proxy for first-party `HttpOnly` cookies in browsers, **or** call the auth endpoints directly with plain `fetch` and `browser_flow: false` from mobile apps, non-browser runtimes, or your own auth proxy server (we hand you the session token directly so you send it subsequently in `Authorization: Bearer` headers). **File storage & email.** Chunked, resumable uploads up to 50 MiB with signed URLs and content sniffing, plus built-in transactional email (**Mailmy**), all accessible via the SDK or standard HTTP `fetch`. ## The shape of a project ```render img:docs-four-pillars|One project contains four pillars: Fleets for server-side code, Database for Postgres tables, Auth for users and sessions, and Storage for files ``` Every project exists in two **environments**: development and production. Each has its own Postgres database, its own Redis database, its own storage files, its own end users, and its own credentials in **Secrets**. You build and break things in development, and when it works, you promote to production. ## Next - [How Fenaura works](/how-it-works): the four pieces and how they meet. - [Environments](/environments): development and production, and what switches between them. - [Quickstart](/quickstart): a working project in one page (SDK and plain `fetch`). - [HTTP fetch & your own backend](/http-and-backends): using Fenaura without the SDK or with your own server. - [Backend auth implementation](/backend-auth-implementation): full server-side auth proxy code. --- # How Fenaura works URL: https://docs.fenaura.dev/how-it-works Section: Getting started # How Fenaura works A Fenaura project has four pieces. This page explains what each one does and how a request moves through them. ## The four pieces **Edge functions** are the only entry point to your backend logic. They run in a V8 isolate, the same engine as a browser tab, without the browser. They start in milliseconds and do not keep state between requests. **The database** is Postgres, and every project gets its own whole database rather than a schema shared with anyone else. You reach it from Fleets with `ctx.db` or `ctx.sql`, and from the browser with the SDK. **Authentication** belongs to the project, not to a third party. End users are rows in your database. The SDK signs them in and stores a session; every edge request carries that session back. **Storage** holds files, split into buckets. Uploads arrive in chunks and retry on failure, so a dropped connection does not lose a 40 MB video. ## How a request travels ```render img:docs-request-lifecycle|A request travels from the browser through the edge runtime session gate into your edge function and Postgres, then back as a 200 response; unauthenticated requests are rejected with 401 before your code runs ``` Two things are worth noticing in that diagram. **Step 2 happens before your code.** You cannot forget to check the session, and you cannot accidentally leave a route open. To serve anonymous traffic you mark a route public on purpose, and then it is public for everyone. **Step 3 gives you a user without parsing anything.** `ctx.user` is already the signed-in end user, as an object, because the platform resolved the session. ## Test and production Every project has two environments of the same code: | | Development | Production | |---|---|---| | Fleet URL | `edge.fenaura.dev/dev-{token}` | `edge.fenaura.dev/{token}` | | Access | requires your dev key or an active dev session | requires a signed-in end user | | Data | separate | real user data | | Keys | separate | separate | You deploy to development, check it, then promote the same code to production. Data does not move with the code, the two environments have their own. ## What Fenaura does not do It is not a place to run long background jobs. An edge request has a time limit, so anything that takes minutes belongs in a queue or a scheduled job you run elsewhere. It is also not a general-purpose host: there is no container, no `npm install` at runtime, and no filesystem that survives a request. ## Next - [Environments](/environments): development and production, and what switches between them. - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Quickstart](/quickstart): build something first. - [Edge functions](/edge): the full surface. - [Projects and organisations](/platform/projects): how work is organised. --- # Environments URL: https://docs.fenaura.dev/environments Section: Getting started # Environments Every project ships with two complete environments: **Development** and **Production**. They are not two views of the same data. They are two separate worlds that happen to run the same code. You switch between them with one control: the **Development | Production** switch in the project header. Flip it and every page in the dashboard switches at once: the database browser, storage, auth users, Fleets, logs, everything. ```render img:docs-dev-vs-prod|Development and production are two separate worlds running the same code; promotion copies code and schema but never overwrites data ``` ## What switches | | Development | Production | |---|---|---| | Database | its own Postgres database | your real database | | Storage | separate buckets and files | real user files | | Redis | its own Redis database | its own Redis database | | Secrets | separate Platform secrets (PG/Redis) & Environment variables | separate Platform secrets (PG/Redis) & Environment variables | | Auth users | test signups only | real end users | | Emails | captured in the sandbox mailbox, never delivered | delivered for real | | Fleets | test deployments | live deployments | Nothing moves between them by default. Trying something in development cannot touch a real user, and a mistake in production cannot corrupt your test data. ## Why this exists Without separate environments, the first real users of your app are also the testers. A schema change meant for testing wipes a production table. A test signup with `test@example.com` sits next to real accounts. An email meant for your own QA list goes to two thousand customers. With separate environments, all of those mistakes are structurally impossible. You build against a copy that looks and behaves like production but holds nothing real. When the code works, you promote it: **promotion copies code, not data.** Your tables, migrations and Fleet deployments move; production data stays exactly as it is. ## Compared to what you may know On most other platforms, a second environment means a second project: you create it, copy the keys, point your code at different URLs, and keep the two in sync by hand. Environment variables drift, one project gets the migration the other missed, and "which database am I looking at" becomes a question you ask more often than you should. Fenaura's version is one project with both worlds inside it. There is no second project to create and no second set of keys to wire: the same Project ID, the same SDK, one switch. The database, storage, Redis, Secrets (**Platform secrets** and **Environment variables**), auth users and email behaviour all switch together, so they cannot drift apart. That is the whole improvement: not more environments, fewer moving parts per environment. ## Both environments share one quota Development and production belong to the same project, and a project has one quota. That is not an oversight: development and production draw from the same pool of database size, Redis memory, file storage and monthly users. If development grows without limit it will consume the budget production needs, and once the pool is full the next request on either side is refused. The limit is a property of the project, not of one environment. The one thing that is free is development email. Messages sent while you are in the development environment are sandboxed: they are recorded in the dashboard and never leave Fenaura, so they cost nothing and cannot reach a real inbox. Production email is the one that counts, because it is actually delivered. ## Development approval (ON by default) Because the Project ID ships inside your app's bundle, **Require approval for development users** is **ON by default** on every new project. Anyone who signs up in development still appears in your **Users** tab, but their session cannot make data or `dev-*` Edge Function requests until you approve them (one click each). Approval takes effect immediately, signup rate limiting tightens, and the pending queue caps at 100 so it cannot be flooded. If you are testing alone and want open development signups without approving each test account, you can turn **Require approval for development users** off in **Auth › Settings**. Still, treat development like a localhost backend: test data only, never real users or real personal information. ## What you get in development Development is where you spend your time, so it is built for speed and safety: - **Sandbox mailbox.** Every email your app sends in development lands in a mailbox inside the dashboard instead of going out. You can read the verification code, the password reset, the welcome email, without owning a single inbox. Nothing is ever delivered to a real address. - **A private dev key (for CLI / server tests).** Non-browser `curl` or backend test scripts can pass `X-Fenaura-Dev-Key` to call `dev-*` Fleet URLs without a browser cookie. Never put `X-Fenaura-Dev-Key` in frontend `VITE_*` variables, signed-in, approved development users authenticate in browsers automatically with `credentials: 'include'`. - **A separate database (rebaseable from Production).** Not a flag on the same tables: a whole database. Migrations, seeds and experiments stay yours. If you created tables while **Production** was selected before testing in Development, **reset / rebase Development from Production** in the dashboard so Development inherits the exact same table schema structure (schema only, zero production rows). - **No verification gate.** The require-email-verification switch applies to production signups only, so a development signup never waits on a code. The dashboard keeps the switch visible in **Auth › Settings** but disables it while the header shows Development, because verification and reset emails are never sent from development at all (the server refuses them outright), so nothing can ever leak to a real inbox. Any app flow that assumes a verification email cannot run in development; design it to be skipped there. - **A real second database.** Development and production are two separate Postgres databases, not two flags on one database. A bug in development cannot write a row a customer will see. The one thing they share is the project quota: pooled database size, storage, Redis and MAU limits count both environments together. - **Deploys that cannot touch production.** Deploying your Fleet to development writes its own development deployment. You can rewrite, break and redeploy your backend all day while production keeps serving live users with the version that is already live. ## Keeping the two databases in sync Because the databases are separate, schema changes do not travel between them on their own. The rhythm that keeps them matching: 1. Change the schema in development (SQL editor or Table Builder, with the header switch on **Development**). 2. Test your code against it. Deploy your Fleet to development as often as you like; production is untouched. 3. When the code works, **promote the schema first**: open **Database › Promote** and start a promotion. Fenaura diffs the two databases, shows you the exact SQL it will run, and applies it to production so the structures match again. Promotion copies structure, never data. 4. Then deploy the code to production. Promote first, deploy second. If you deploy code that expects a column before promoting the schema, the first production request fails, not because the deploy was wrong but because production's database has not caught up yet. If you created tables while **Production** was selected before testing in development, go the other way: open **Database › Promote** and use **Reset Development to match Production** so development inherits the exact same schema structure (with zero production rows). ## Using the SDK in development One option on the client moves your whole app into the development world: ```ts // while building and testing: export const fenaura = createClient('/fenaura', 'your-project-id', { env: 'development', }); // in your live build: no option, or env: 'production' export const fenaura = createClient('/fenaura', 'your-project-id'); ``` With `env: 'development'`, signing up creates a **development user**: a row in the development environment that production never sees. No verification email is sent and none is expected; the session starts immediately, so testing a signup is one call. Every request that session makes afterwards, including database reads and writes and file storage, resolves against the development database, because the session itself carries the environment. And because the frontend is just a client, it does not have to live anywhere in particular: host the same codebase on another domain, far from your users, or run it locally on your laptop. It all works, because the SDK only needs the proxy path and the Project ID. That is what makes a real beta possible: a hundred people can sign up to your development environment and test your app for you, and production never sees a single one of them. Development approval is ON by default, so each of them waits in **Auth › Users** until you approve them, and until then their session cannot make data requests (`DEV_NOT_APPROVED`) even though signup itself succeeded. Once approved they use the app exactly as production users do, so anything that works for them in development works the same in production. The Project ID stays the same in both modes. You are not pointing at two different projects; you are telling one project which of its two worlds to use. A common setup sets the option from your bundler's dev flag: ```ts export const fenaura = createClient('/fenaura', 'your-project-id', { env: import.meta.env.DEV ? 'development' : 'production', }); ``` Vite and most modern bundlers define a build-mode flag such as `import.meta.env.DEV` so development builds land in the development environment with no manual switching. One session per browser: the development and production sessions of a project share one cookie name, so signing into one replaces the other in the same browser. On localhost that never comes up, because localhost and your live domain are different cookie jars anyway. ## How it works in code Your frontend code does not change between environments. For Fleets, the two environments have different fleet URLs, and your data requests carry the project ID plus the session the platform issued for that environment. You deploy the same build twice, once per URL. The things that differ are the values you keep in the two environments: ```ts // A key set in development is undefined in production, and the other way // around. Read env vars defensively so the failure is clear: const secret = ctx.env.STRIPE_SECRET_KEY; if (!secret) { return Response.json( { error: 'STRIPE_SECRET_KEY is not set in this environment' }, { status: 500 }, ); } ``` Set each variable in both environments. The dashboard shows them side by side, so a missing one is visible at a glance. ## The usual rhythm 1. Build and test in **Development** with sandbox data and sandbox email. 2. Promote to **Production** when the code works. 3. Watch the first production requests in the logs. 4. Keep developing: production keeps serving while you work in development. ## Next - [Quickstart](/quickstart): build your first project before switching environments. - [How Fenaura works](/how-it-works): the four pieces and how they meet. - [Edge environments](/edge/environments): dev URLs, the dev key, and promotion for Fleets. - [Auth overview](/auth): how sessions differ between environments. --- # Quickstart URL: https://docs.fenaura.dev/quickstart Section: Getting started # Quickstart This page takes you from nothing to a signed-in database query. You need a frontend project to run the installer in, because the session cookie has to be set by your own domain (that is the proxy, explained in [createClient](/sdk/create-client)). If you do not have one yet, an empty folder with a `package.json` is enough to start; any framework works. ## 1. Create your organization and project Sign in at [fenaura.dev](https://fenaura.dev). Everything lives inside an organization, so the first screen is **Organizations**: click **New organization**, name it, and open it. Inside, click **Create project** and give the project a name. Creating it provisions the database, the auth system and a storage bucket with it. The free plan allows 2 active projects per account, across all of your organizations combined (see [Quotas](/platform/quotas) for the honest details, including the workaround we are cheekily aware of). Open the project. The sidebar (or the menu, on a phone) lists its pages; the first one is **Project Overview**. ## 2. Install the SDK and wire the proxy In your frontend project folder: ```bash npm install fenaura-sdk npx fenaura-auth-init ``` The first line installs the SDK. The second is the auth wiring: it detects your host and writes the proxy files that carry sign-in traffic. Run it and you will see something like: ```text ✓ Fenaura auth proxy setup - done wrote public/_redirects wrote vercel.json wrote vite.config.ts (added server.proxy) ``` They land in your project root next to `package.json`: ```render component:auth-init-files ``` Only one proxy file is active at a time (`vercel.json` on Vercel, `public/_redirects` on Netlify and Cloudflare Pages, and `server.proxy` in `vite.config.ts` during local dev). Each one forwards `/fenaura/...` requests to Fenaura so your session cookie stays on your own domain. See [Installation](/sdk) for every host. ## 3. Copy the Project ID Back on **Project Overview**, copy the **Project ID** with the Copy button next to it. That is the only value your frontend needs. There is no secret in it and there is nothing else to configure; [createClient](/sdk/create-client) explains why the Project ID is safe to ship. You will also see a **Project Secret Key** on the same page, marked *Server API* and *Keep secret*. You do not need it for anything on this page. It is for backend calls that act with full project authority, and it never goes into browser code. ## 4. Call createClient Create a `fenaura.ts` file and export your client once: ```ts // fenaura.ts import { createClient } from 'fenaura-sdk'; export const fenaura = createClient('/fenaura', 'your-project-id'); ``` Two arguments, in this order: the proxy path, then your Project ID. Copy the ID straight from the dashboard. If you prefer environment variables, they work too, but they are optional; see [createClient](/sdk/create-client). ## 5. Sign an end user up ```ts const { data, error } = await fenaura.auth.signUp({ email: 'ada@example.com', password: 'a-long-enough-password', }); if (error) throw error; // data.session_minted === true: the user exists and is signed in ``` By default, signing up creates the user and starts the session in one step. Fenaura sets the session cookie in the browser; your code stores nothing. If you want your users to verify their email before signing up, it is just a single toggle in **Auth › Settings** (**Require email verification**), with no SMTP server or extra config required. See [Sign-up and sign-in](/auth/methods) for the verification code flow, or [Pure fetch & mobile API](/sdk/fetch) if you are calling the HTTP API without `fenaura-sdk`. ## 6. Create the `notes` table and write a row First, make sure the environment switcher in the dashboard header is set to **Production** (we are testing against Production first because it is the fastest path end-to-end; if you create the table while **Development** is selected, your Production database will not have `notes` yet). Create a `notes` table in **Database › Tables** (the visual Table Builder pre-populates `id`, `owner` with `DEFAULT auth.uid()`, `created_at`, and the **Own rows only** RLS preset, then add a `title` column of type `text`) or run this in **SQL Editor**: ```sql CREATE TABLE IF NOT EXISTS notes ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), title text NOT NULL, owner uuid DEFAULT auth.uid(), created_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE notes ENABLE ROW LEVEL SECURITY; CREATE POLICY allow_owner_select ON notes FOR SELECT USING (owner = (SELECT auth.uid())); CREATE POLICY allow_owner_insert ON notes FOR INSERT WITH CHECK (owner = (SELECT auth.uid())); CREATE POLICY allow_owner_update ON notes FOR UPDATE USING (owner = (SELECT auth.uid())) WITH CHECK (owner = (SELECT auth.uid())); CREATE POLICY allow_owner_delete ON notes FOR DELETE USING (owner = (SELECT auth.uid())); ``` Then insert a row from your frontend. Because `owner` defaults to `auth.uid()`, Postgres fills it automatically from the signed-in session: ```ts const { data, error } = await fenaura .from('notes') .insert({ title: 'First note' }) .execute(); ``` You can also choose to pass the owner yourself, and it becomes the other way round with the same idea: now your code supplies the value and Postgres accepts it because it matches the signed-in user the policy demands: ```ts const me = (await fenaura.auth.getUser()).data.user; const { data, error } = await fenaura .from('notes') .insert({ title: 'First note', owner: me.endUserId }) .execute(); ``` Both forms insert the same row. Leaving `owner` out is the common choice; pass it explicitly when your code already has the user id in hand. Every method returns `{ data, error }`. Nothing throws, so check `error` instead of wrapping calls in `try`. ## 7. Read rows back ```ts const { data: notes } = await fenaura .from('notes') .select('*') .order('created_at', { ascending: false }) .limit(20) .execute(); ``` The builder is awaitable on its own, so `.execute()` is optional here. The docs always show it, so you never have to remember which calls need it. ## Where to go next - [Your first Fleet & Development testing](/first-fleet-and-dev-testing): write and deploy your first Fleet (`main.ts`), call it over HTTP, and opt into isolated Development testing. - [HTTP fetch & your own backend](/http-and-backends): use plain `fetch` or connect your own backend server directly over Postgres TLS and Redis TLS. - [Backend auth implementation](/backend-auth-implementation): the full server-side auth proxy code. - [Environments](/environments): development and production, and what switches between them. --- # Your first Fleet & Development testing URL: https://docs.fenaura.dev/first-fleet-and-dev-testing Section: Getting started # Your first Fleet & Development testing In the [Quickstart](/quickstart), you created a `notes` table, inserted a row, and read rows back with `fenaura-sdk`. Now we will run the exact same operations through a **Fleet** (Fenaura's edge function), deploy it, and then switch into the isolated **Development** environment for safe beta testing. ## 8. Write your first Fleet (`main.ts`) In steps 6 and 7 you inserted a note and read notes back **with the SDK**. You already know the job: take a title from your app, store it against the signed-in user, read that user's rows back. Now we are going to do the exact same two operations with a **Fleet** (Fenaura's edge function), so you can see that it is the same job with a different doorway. Your backend code lives in `main.ts` inside **Fenaura Fleets** (what Supabase and other platforms call Edge Functions). You do not need to wrap it in an `export default` function; the Fleets IDE wraps `main.ts` for you automatically. Use a simple `if` statement on `req.method` and `req.path` so your Fleet handles both `POST /api/notes` (creating a note from the request body) and `GET /api/notes` (reading your notes back). Write this directly in `main.ts`: ```ts // main.ts if (req.method === 'POST' && req.path === '/api/notes') { const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); const title = String(body.title ?? '').trim() || 'From my first Fleet'; const [note] = await ctx.db.query( 'insert into notes (title, owner) values ($1, $2::uuid) returning *', [title, ctx.user.userId], ); return ctx.json({ note }, 201); } if (req.method === 'GET' && req.path === '/api/notes') { const notes = await ctx.db.query( 'select * from notes where owner = $1::uuid order by created_at desc limit 20', [ctx.user.userId], ); return ctx.json({ notes }); } // If the request does not match any handler above, this runs as a catch-all for unhandled routes or methods return ctx.json({ error: 'Not found' }, 404); ``` A few things to notice here: - **The `/api` part is yours, not ours.** Nothing in Fenaura requires your routes to start with `/api`. After your Fleet's base URL, Fenaura does not know anything about your URLs and does not want to: you define them in `main.ts` and you call them. `/api/notes` is simply the route you chose, the same way you would choose it on your own server. You could have written `/notes`, `/v1/notes` or `/make-a-note`; whatever you define is exactly what you call. - **Why `req.method` is there.** Your Fleet's base URL is one URL, but a request has two halves: the method (`GET`, `POST`, `PUT`, `DELETE`) and the path (`/api/notes`). `req.method` tells you which of the two the caller wants, because `GET /api/notes` (read my notes) and `POST /api/notes` (create a note) hit the same path but must do completely different things. - **Why `req.path` is there too.** Remember that Fenaura gives you a base URL and everything after that base URL arrives inside the `req` object, just like it does on your own Express or Hono server. So treat `main.ts` like your server's request handler: `req.path` is the path the caller asked for. Without checking `req.path`, every `POST` or `GET` to **any** path on your Fleet URL would fall into those blocks. For real apps, we do not grow `if` chains: Fenaura Fleets has **Hono** built in (`app.get(...)`, `app.post(...)`, route params, and middleware), see [Fleets Routing](/fleets/routing). - **The final `return` is not Fenaura syntax.** That last block, the one commented as the catch-all, is plain JavaScript doing what an Express server does: your file runs from top to bottom, each `if` gets a chance to handle the request, and if nothing matched, execution falls through to the last statement, which answers `404 Not found`. There is no special Fenaura routing magic involved; it is the ordinary "routes from top to bottom, then the fallthrough" pattern you already know from Express. We call it out with a comment only so the shape is familiar, not because the platform requires it. - **Body validation & npm packages.** You can install npm packages like `zod` (see [Using npm packages](/fleets/ide#using-npm-packages)) to validate request bodies, though we use the quick `typeof req.body` check above to keep this walkthrough fast. - **What is available on `ctx` out of the box.** Every Fleet comes pre-wired with what you need for a full backend with zero connection strings or client setup: Postgres (`ctx.db`, `ctx.sql`, `ctx.pg`), project-isolated Redis (`ctx.redis`), file storage (`ctx.storage`), image transforms (`ctx.image`), email (`ctx.email`), environment secrets (`ctx.env`), verified user identity (`ctx.user`), structured logging (`ctx.log`), and background tasks (`ctx.waitUntil`). See [The context object](/fleets/context) for the complete list of everything built into Fleets out of the box. - **No `if (!ctx.user)` check needed on private routes.** Fenaura checks the caller's session before your function starts. As long as the route is not marked public, unauthenticated requests receive `401` before your code runs, so `ctx.user` is already populated when your handler executes. - **`ctx.db.query(sql, params)`** runs parameterized SQL against your project's database and returns an array of row objects (see [The database](/fleets/database) for Drizzle and transactions). - **`ctx.json(data, status)`** sends a JSON response (returning a plain object like `{ notes }` also works). ### Deploying it: the actual clicks Now put the code live. The steps below are the real ones, including the checks Fenaura asks for on the way. **On desktop:** 1. In the Fleets IDE header, click the **⋯** (more actions) button at the top right, next to the Dev/Prod working-environment switch. 2. In the menu, scroll to the **Advanced · Deployment & Run** section. 3. Click **Make live in Production**. 4. A dialog opens: **Make this version live?** It asks for two things, and both are required: - a **deploy message** (what changed, e.g. "Add task routes, validation and DB queries"). It is recorded in your version history. - a **typed confirmation**: type your project's slug into the confirm field. This is deliberate: production is your live backend, so publishing is never a one-click accident. 5. The dialog also shows you which Git commit will go live, and it checks your working tree. If you have **uncommitted changes**, the deploy is blocked: production deploys an exact, permanent commit, so the dialog shows a red banner with the uncommitted file count and a **Review & commit** button. Click it, commit your changes, and start the deploy again. 6. Click **Make live in Production** in the dialog. The terminal in the IDE shows the bundling and deploy progress, and the version appears in **Versions & Timeline**. **On mobile:** 1. Open the Fleets IDE. The header shows a **Back** button, a **folder icon** (opens the file explorer drawer) and the **⋯** more-actions button. 2. Tap **⋯**. 3. In the menu, scroll to **Advanced · Deployment & Run**. 4. Tap **Make live in Production**. 5. The same dialog appears, with the same checks: deploy message, typed project slug confirmation, and the uncommitted-changes block if you have edits you have not committed (tap **Review & commit**, commit, retry). 6. Tap **Make live in Production** and watch the terminal panel for progress. For a test round that must not touch production, the same menu has **Deploy to Development**: it asks only for an optional message and publishes to your development environment, leaving production untouched. One more thing worth knowing: Fenaura talks to your Fleet over **pure HTTP**. There is no Fenaura-specific protocol, SDK requirement or plugin to install on the calling side; any HTTP client anywhere can call your Fleet URL. That is why a Fleet behaves like an actual server you own: point anything at it, a browser, a phone app, a cron job on a VPS, a webhook from a payment provider, and it answers. ## 9. Run it Copy your **Fleet URL** from **Project Overview** (the dropdown defaults to **Fleet (Browser)**, e.g. `/fenaura/fleet/k7m9x2p`, and switches to **Full Fleet URL**, e.g. `https://edge.fenaura.dev/k7m9x2p`, for non-browser clients). Save it in a variable and call your routes: ```ts // Copied from Project Overview -> Fleet URL (Fleet (Browser)) const FLEET_URL = '/fenaura/fleet/k7m9x2p'; // 1. Create a note (hits `POST /api/notes` in main.ts) const createRes = await fetch(`${FLEET_URL}/api/notes`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'From my first Fleet' }), }); if (!createRes.ok) { const err = await createRes.json(); if (createRes.status === 401) throw new Error(err.message); throw new Error(`${err.code}: ${err.message}`); } const { note } = await createRes.json(); // 2. Read your notes back (hits `GET /api/notes` in main.ts) const listRes = await fetch(`${FLEET_URL}/api/notes`, { credentials: 'include', }); if (!listRes.ok) { const err = await listRes.json(); if (listRes.status === 401) throw new Error(err.message); throw new Error(`${err.code}: ${err.message}`); } const { notes } = await listRes.json(); ``` ### From a browser, always the proxy URL In browser code, always use the `/fenaura/fleet/...` proxy path and never call `https://edge.fenaura.dev/...` directly. Fenaura keeps user sessions in first-party `HttpOnly` cookies on **your** domain, so cross-origin requests straight to `edge.fenaura.dev` carry no cookie and fail with `401`. Calling through `/fenaura/fleet` keeps requests same-origin so the session cookie rides along automatically. On every plain browser `fetch`, pass `credentials: 'include'` so the browser attaches that session cookie (`fenaura-sdk` sets this automatically): ```ts const res = await fetch(`${FLEET_URL}/api/notes`, { credentials: 'include' }); ``` ### Outside a browser (mobile, desktop, CLI, server) Non-browser clients (mobile apps, desktop/PC apps, CLIs, webhooks, or your own backend) have no browser cookie jar, so switch the **Fleet URL** dropdown to **Full Fleet URL** and send requests directly: ```ts const FLEET_URL = 'https://edge.fenaura.dev/k7m9x2p'; const res = await fetch(`${FLEET_URL}/api/notes`, { headers: { Authorization: `Bearer ${sessionToken}` }, }); ``` To get a session token without cookies, pass [`browser_flow: false`](/sdk/fetch#sign-in-server-mobile-cli-browserflow-false) when signing in (or [signing up](/sdk/fetch#sign-up-server-mobile-cli-browserflow-false)). Outside the browser, storing that end-user token securely (iOS Keychain / Android Keystore / `SecureStore` on mobile, OS credential storage or encrypted config on PC) is the developer's responsibility. Read it from your secure store and attach it as `Authorization: Bearer ` on each request. For development-only CLI or server scripts targeting `dev-k7m9x2p`, pass `X-Fenaura-Dev-Key`. ### Opting into Development testing When you are ready to isolate testing from live data, switch to **Development**. This is the part we are genuinely proud of, because it gives you something most platforms make you pay for or bolt together yourself: a complete second world for your app, with your production one untouched and still serving live users while you test. **Step 1: flip the switch in the dashboard.** In your project header there is a **Development | Production** switch. Flip it to **Development** and every dashboard page (database, users, storage, Fleets, logs) now shows the development world. **Step 2: point a frontend at it.** Your frontend code does not have to live inside the dashboard. Take the same frontend codebase and host it anywhere you like, on Vercel, on a different domain far from your users, or just run it locally on your laptop; it all works, because the SDK only needs the proxy path and your Project ID. In that testing frontend, pass the environment to the client: ```ts export const fenaura = createClient('/fenaura', 'your-project-id', { env: 'development', }); ``` That one option moves every signup, session and query this client makes into the development world. **Step 3: sign people up.** With `env: 'development'`, every signup creates a **development user**: the account is created, but it appears in your **development** user list, never in production, and **no verification email is sent**, none, ever. There is no code to wait for, so a test signup is one call. That is deliberate: verification emails are a production feature, and development has no way to send them (the server refuses verification and reset mail in development outright, so nothing can ever leak to a real inbox). Any flow in your app that assumes a verification email should be designed around this: in development those flows simply cannot run, and that is by design. And here is the part that makes it scale: because signups are cheap and safe, you can have **a hundred people sign up to your development environment and test your app for you**, while production never sees a single one of them. Your own private beta crowd, on the same project, for free. **Step 4: approve your testers.** Fenaura is careful about who gets into your app, even in development. Since your Project ID is public, just knowing it would let anyone sign up, so development approval is **ON by default**: a new development signup lands in your **Auth › Users** tab marked as pending, and here is the secure part, **they do not get a working session**. They can sign up, but every data request their session makes is refused with `DEV_NOT_APPROVED` until you act. To let someone in, open **Auth › Users** in development, find the pending user, and approve them as a tester, or select multiple rows with the checkboxes to bulk **Approve** and **Reject** (unapprove) testers at once, just like you can bulk select users to **Revoke** or **Delete** them. From that moment Fenaura grants their session access and they can use your app like anyone else. So the gate is real: nobody uses your app in development unless you said so (you can switch the gate off in **Auth › Settings** when you are testing alone). **Step 5: use the app exactly like production.** This is the sweet part: your testers are using your app **the same way as in production**. Same code, same flows, same SDK calls; the only difference is which world the session points at. So if your frontend is hosted somewhere, any change you make there that works in development works exactly the same when it meets production. And your Fleet code is isolated the same way: deploy your edge function to **Development** (the IDE's **Deploy to Development** menu item) and you can rewrite, break and fix your backend all day, production never notices. Do every single thing, while production stays up serving live users. **Step 6: keep the two databases in sync.** Development and production each have their **own separate database** (a real second Postgres database, not a flag), which is what makes all of the above safe. The one thing they share is the project's **quota**: the pooled database size, storage, Redis and MAU limits are per project across both environments, so testing in development counts against the same budget production will need. Because the databases are separate, schema changes do **not** travel on their own. The rule that keeps the pair healthy: whenever you change the schema in development (new table, new column), the two structures drift apart until you move the change over. Before you deploy the matching code to production, go to **Database › Promote** and **promote** the schema: Fenaura diffs the two databases, shows you the exact SQL it will run, and applies it to production so the structures match again (promotion copies structure, never data). Promote first, deploy second, and the two worlds stay in lockstep. The same discipline applies inside development: if you created `notes` (or any other tables) while **Production** was selected, open **Database › Promote** and use **Reset Development to match Production** so your development database inherits the exact same schema structure (with zero production rows) before you test against it. To call your dev Fleet from that testing frontend, deploy the function to **Development** and copy the **Fleet (Browser)** URL from **Project Overview** while **Development** is selected in the environment switcher (`/fenaura/fleet/dev-k7m9x2p`, with `credentials: 'include'`). No `X-Fenaura-Dev-Key` is needed in browser code; your approved development session cookie routes everything automatically. See [Environments](/environments) for everything you need to know about Development vs. Production, user approval, rebasing schemas, and CLI/server testing with `X-Fenaura-Dev-Key`. **Why there is no function name in the URL:** Notice that `/fenaura/fleet/k7m9x2p` is your Fleet's base URL and `/api/notes` is a route inside `main.ts`, not a separate function deployment. In Fenaura's model, you do not deploy separate URLs per function. Instead of growing `if` blocks, real Fleets use **Hono** (`app.get`, `app.post`, sub-routers, and controllers), see [Fleets Routing](/fleets/routing). ## Where to go next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [HTTP fetch & your own backend](/http-and-backends): use plain `fetch` or connect your own backend server over Postgres TLS and Redis TLS. - [Backend auth implementation](/backend-auth-implementation): the full server-side auth proxy code. - [Environments](/environments): development and production, and what switches between them. - [How Fenaura works](/how-it-works): what each piece does. - [Auth methods](/auth/methods): the sign-up flow, verification, and every auth call. - [Querying](/database/querying): the full builder. - [Fleets](/fleets): routing, the context object, and errors. --- # HTTP fetch & your own backend URL: https://docs.fenaura.dev/http-and-backends Section: Getting started # HTTP fetch & your own backend Fenaura speaks plain HTTP. The SDK is optional, every auth and data endpoint works with standard `fetch`, and your own backend connects directly to your project's PostgreSQL and Redis with normal drivers. Even if you only need a standalone PostgreSQL database or a standalone Redis database on its own, without using Fleets or Auth, Fenaura has you covered: grab your TLS credentials from **Secrets › Platform secrets** and connect straight from your own server. ## Pick your architecture | Architecture | Client transport | Backend compute & DB | |---|---|---| | **Full-stack Fenaura** | `fenaura-sdk` (or plain `fetch`) via the same-origin `/fenaura/*` proxy | **Fenaura Fleets** (`ctx.db`, `ctx.sql`, `ctx.redis`) against the project's isolated Postgres and Redis | | **Custom auth proxy / mobile** | Web frontend talks only to **your own backend** (never to Fenaura directly); or mobile/CLI calls `https://api.fenaura.dev` directly with `browser_flow: false` | **Your own backend** (Express, Fastify, FastAPI, Go, Spring, Rails) forwards auth to Fenaura, sets an `HttpOnly` cookie, and connects directly to Fenaura's isolated **Postgres TLS** and/or **Redis TLS** via **Secrets › Platform secrets** (or your own DB) | | **Database or Redis only** | Your own frontend talking strictly to your own backend | **Your own backend** connecting directly to Fenaura's isolated **Postgres TLS** and/or **Redis TLS** with standard drivers | | **Hybrid** | Frontend uses `fenaura-sdk`, `/fenaura/*`, or your own backend proxy | Both Fleets (`ctx.db`) and your external backend talk to the same isolated project Postgres database and Redis | Your server can also send requests to your Fenaura Fleets on behalf of an end user. Forward that user's session token and Fenaura validates it before your Fleet runs, so `ctx.user` is the same verified user. This is also ideal if you do not want anyone to see that you are using Fenaura in your frontend code, or if you want to run your own server-side logic before your Fleet executes: your frontend calls your own server, your server runs its checks, and then your server forwards the authenticated request to your Fleet. Section 3 shows the call with the `notes` example from earlier. ## 1. Frontend: SDK or plain `fetch` In web browsers, `fenaura-sdk` wraps `fetch` and uses a same-origin `/fenaura/*` proxy so session cookies (`HttpOnly`, `Secure`, `SameSite=Lax`) are set on your domain. You do not **have** to install the SDK. Any framework, vanilla script, mobile client, or server can send plain HTTP requests to the same endpoints: - **Browser with proxy:** send `fetch('/fenaura/...')` with `credentials: 'include'`. - **Server / Mobile / CLI (direct URL, no proxy):** send `fetch('https://api.fenaura.dev/...')` directly, and include `"browser_flow": false` in auth JSON bodies (or header `X-Fenaura-Browser-Flow: false`). Fenaura returns the session token in `data.token`, so send it on later calls as `Authorization: Bearer `. See [Pure fetch & mobile API](/sdk/fetch) for request snippets, [All Direct API URLs](/platform/direct-urls) for every direct `https://api.fenaura.dev` endpoint on one page, and [API Responses & Status Codes](/platform/responses-and-status-codes) for every response and error shape. ## 2. Use Fenaura for auth only (your own backend) If you already have your own backend and database, your frontend can talk strictly to your server, and your server can use Fenaura only for authentication. The flow is: your frontend posts credentials to your routes, your server forwards them with `"browser_flow": false` to `https://api.fenaura.dev/auth/dp/signup`, `/auth/dp/verify-email`, `/auth/dp/login` and `/auth/dp/whoami`, then sets a first-party `HttpOnly` cookie on your own domain. **The complete code implementation is on the next page, [Backend auth implementation](/backend-auth-implementation):** all four Express/Node routes, both signup branches (email verification on and off), the 6-digit code screen, the `HttpOnly` cookie helper, session validation with `whoami`, and caching the verified user in your own database. If you want to copy working server code, go there next. ## 3. Calling your Fenaura Fleets from your server Every Fleet has **one URL** that you copy directly from **Project Overview › Fleet URL**: - **Fleet (Browser):** `/fenaura/fleet/...` (for browser apps using the same-origin proxy). - **Full Fleet URL:** `https://edge.fenaura.dev/...` (switch the dropdown in **Project Overview › Fleet URL** to **Full Fleet URL** and copy it for server, mobile, CLI, or webhook calls). - **Development vs Production:** flip the **Dev / Prod** switch at the top of the dashboard to copy the `dev-` development URL or the production Fleet URL. - **Calling `dev-` from a server, CLI or API tester without a user session:** include `X-Fenaura-Dev-Key: ` (copy it from **Project Overview › Dev private key**). The gateway verifies the key and resolves your own developer mirror identity, because you are a user in your own app. Any Fleet code that reads `ctx.user` therefore gets `{ userId, id, identifier }` instead of `undefined`, and RLS plus every downstream check see that same user. You do not need to copy a browser cookie or session token. **There is no separate public URL vs private URL.** Every route in your Fleet uses the exact same Fleet URL copied from your dashboard: - By default, routes require a valid end-user session. When your backend sends `Authorization: Bearer `, Fenaura validates the session at the gateway, strips `authorization` and `cookie` before your V8 isolate runs, and populates `ctx.user` (`{ userId, id, identifier }`). - To make a route public (accessible without a user session, such as a webhook or public listing), mark that route public in your Fleet controller options: ```ts // Public route: no end-user session required (same Fleet URL!) app.get('/api/health', { public: true }, (c) => c.json({ ok: true })); // Shorthand helpers also work: app.publicGet('/api/health', handler) // Private route (default): requires a verified end-user session in ctx.user app.post('/api/notes', async (c) => { const { title } = await c.req.json(); const [note] = await c.env.db.query( 'INSERT INTO notes (title, owner_id) VALUES ($1, $2) RETURNING *', [title, c.env.user.userId], ); return c.json({ note }, 201); }); ``` Routing through your own server is useful in two common cases: - **Hide Fenaura from your frontend completely:** your browser or mobile app only talks to your own API domain (`/api/notes`), with zero Fenaura URLs or headers exposed in client code. - **Run custom logic before your Fleet executes:** validate payloads, check billing quotas, enrich data, or call an internal service on your server first, then forward the verified user's session token to your Fleet. ### Responses returned from Fleets When your backend forwards a request to your Fleet URL, the response comes from one of two places: - **Fenaura gateway (before your Fleet runs):** if a private route is called without a valid session, or if origin / rate-limit checks fail, Fenaura rejects the request at the gateway with a structured error JSON payload (for example `401 SESSION_MISSING`, `401 INVALID_SESSION`, `429 RATE_LIMITED`). Your Fleet handler does not execute. - **Your Fleet handler (after checks pass):** once the gateway passes, your Fleet runs with `ctx.user` populated and Fenaura forwards the exact HTTP status code and response body your Fleet returned (for example `201 { note }` or your own validation error like `400 { error: "..." }`). See [API Responses & Status Codes](/platform/responses-and-status-codes#fleets-edge-functions) for the complete list of gateway vs handler responses. Here is the `POST /api/notes` saving example from [Your first Fleet & Development testing](/first-fleet-and-dev-testing), routed through your own backend server before hitting your Fenaura Fleet: ```ts // 1) Browser frontend: talks only to YOUR server (zero Fenaura URLs in frontend code) const res = await fetch('/api/notes', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Ship v1' }), }); const { note } = await res.json(); ``` ```ts // 2) Your own backend server (Express / Fastify / Hono / etc.) // Copy directly from Project Overview -> Fleet URL -> Full Fleet URL const FLEET_URL = 'https://edge.fenaura.dev/k7m9x2p'; app.post('/api/notes', async (req, res) => { const token = req.cookies.session; if (!token) return res.status(401).json({ error: 'signed_out' }); // Run any custom server-side logic before your Fleet runs const title = String(req.body?.title ?? '').trim(); if (!title || title.length > 140) { return res.status(400).json({ error: 'Title must be between 1 and 140 characters.' }); } // Forward the verified user's session token to your Fenaura Fleet // Fenaura validates the token and populates ctx.user before your handler runs const fleet = await fetch(`${FLEET_URL}/api/notes`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, // Only needed if Allowed Origins is non-empty on this project: // Origin: 'app://my-backend', }, body: JSON.stringify({ title }), }); // Returns either Fenaura's gateway error (e.g. 401 SESSION_MISSING) // or your Fleet handler's own status code and JSON body const payload = await fleet.json(); return res.status(fleet.status).json(payload); }); ``` Two rules keep this reliable: - **Always copy the exact Fleet URL from Project Overview › Fleet URL** (never construct URLs manually from slugs). Add `X-Fenaura-Dev-Key` when testing the `dev-` URL without an end-user session, and your Fleet's `ctx.user` will be your own developer identity. - **If you have locked down Allowed Origins**, add a non-HTTP custom origin for your backend (for example `app://my-backend`) under **Settings › Domains & Origins** and send it in the `Origin` header on server calls. ## 4. Database & Redis directly from your own backend If you use Fenaura only for Auth (or even without Auth), your own backend can connect directly to Fenaura's isolated **Postgres TLS** and/or **Redis TLS** using standard drivers without calling Fenaura's HTTP data APIs for anything else. Open **Database** in the sidebar for the live connection facts (host, port, user, SSL) of the selected environment. Open **Redis** for the key browser, memory usage, and command console. Copy the full TLS connection strings from **Secrets › Platform secrets**. - **PostgreSQL over TLS (`:5432`):** `DATABASE_PUBLIC_URL`, `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`, `PGSSLMODE=require`. Connect with `pg`, Drizzle, Prisma, `psycopg`, SQLAlchemy, `pgx`, `GORM`, `sqlx`, JDBC, or `PgBouncer`. - **Redis over TLS (`:6380`):** `REDIS_PUBLIC_URL`, `REDISHOST`, `REDISPORT`, `REDISUSER`, `REDISPASSWORD`. Connect directly with `ioredis`, `node-redis`, `redis-py`, `go-redis`, or `lettuce`. Every project database is isolated under its own TLS-authenticated role with `CONNECTION LIMIT 20`. That is a ceiling on simultaneous Postgres sessions, not a queries-per-second limit. It is comfortable for one persistent backend using a small shared connection pool (5-10 connections). It becomes a problem only if you open a fresh connection per request, or run many serverless instances that each keep a 10-connection pool. Create one pool at module scope, size it below 20, and put PgBouncer in transaction mode in front of the database if you need many more concurrent clients. Your application-side pool and any server-side pooler both draw from the same 20-connection budget. For scale reference, Supabase's free (Nano) compute allows 60 database connections, 200 pooler clients, and a default server-side pool size of 15. Its shared transaction pooler exists for the same reason: short-lived serverless connections exhaust direct limits quickly. Fenaura's 20 is in the same practical class, a small pooled budget that is fine for normal apps when the client pools connections instead of opening one per request. Redis is a real, TLS-encrypted Redis database for the environment, with its own keys, memory usage, and command console. TTLs are capped at 30 days. See [External Postgres & Redis](/database/external-connections) for ready-to-paste client snippets across languages. ## Next - [Backend auth implementation](/backend-auth-implementation): the complete server-side auth proxy code (the next page). - [Direct API URLs Reference](/platform/direct-urls): every code-verified direct Fenaura URL (`https://api.fenaura.dev`, `wss://api.fenaura.dev`, `https://edge.fenaura.dev`) on one page. - [API Responses & Status Codes](/platform/responses-and-status-codes): every success and error response shape across Auth, Fleets, Data, Storage, Realtime, and SDK. - [External Postgres & Redis](/database/external-connections): connect `pg`, Drizzle, Prisma, `psycopg`, `pgx`, and `ioredis` via **Platform secrets**. - [Pure fetch & mobile API](/sdk/fetch): every auth, OAuth, password reset, query, storage, and email request in raw HTTP. - [Authentication methods](/auth/methods): full details on `browser_flow`, cookies, metadata, and verification codes. --- # Backend auth implementation URL: https://docs.fenaura.dev/backend-auth-implementation Section: Getting started # Backend auth implementation This page is the code implementation for the **your own backend** architecture introduced on the previous page, [HTTP fetch & your own backend](/http-and-backends). It shows every route you need to use Fenaura for authentication while your frontend talks only to your server: signup with optional verification codes, login, a first-party `HttpOnly` cookie, session validation on later requests, and caching the verified user in your own database. ## How the proxy works If you already have your own backend and database (or want Fenaura completely hidden from browser network tabs), your own frontend talks **strictly to your own backend**. You only use Fenaura for authentication. > **Do this first: turn on email verification for auth.** Open your project's **Auth Settings > General** and tick **Require email verification before first session**, then save: > ```render ``` > **This will not work if you skip it.** With the switch off, signup mints a session immediately, no 6-digit code is emailed, `data.verification_required` never comes back, and your `/api/verify-email` route below is never reached. The proxy example further down assumes verification is ON. See [Authentication methods](/auth/methods) for the full switch walkthrough. ### Step 1: Your frontend sends credentials to your backend Your frontend posts to your own routes (`POST /api/signup`, `POST /api/login`, `POST /api/verify-email`) and never calls `api.fenaura.dev` directly. ### Step 2: Your backend forwards the auth request to Fenaura Include `"browser_flow": false` in the JSON body (and `"env": "development"` for development; omit `env` for production). You can also include an optional `metadata` JSON object (up to 16 KiB) on signup, which Fenaura saves to `end_users.metadata` and syncs to `public.users.metadata`. **Login (`POST https://api.fenaura.dev/auth/dp/login`)** returns the session token immediately: ```json { "status": "success", "data": { "token": "", "session_minted": true } } ``` **Signup when email verification is OFF (`POST https://api.fenaura.dev/auth/dp/signup`)** creates the user and mints a session immediately: ```json { "status": "success", "data": { "token": "", "session_minted": true, "pending_approval": false } } ``` **Signup when email verification is ON in Auth Settings (Production)** creates the unverified user, emails a 6-digit verification code, and returns **no token yet**: ```json { "status": "success", "data": { "verification_required": true, "code_already_sent": false, "already_pending": false, "email": "ada@example.com", "message": "A verification code was sent to ada@example.com. Submit it to complete signup.", "expires_in": 600, "expires_in_display": "10 minutes" } } ``` **What this object means and how to use every property in your app:** | Property | Type | What it is and what you can do with it | |---|---|---| | `verification_required` | `boolean` (`true`) | Tells your frontend and backend that **no session token or cookie exists yet**. Branch on `data.verification_required === true` to show your 6-digit code screen instead of signing the user in. | | `code_already_sent` | `boolean` | `false` when Fenaura just sent a fresh code; `true` when an active unexpired code was already sent earlier (Fenaura keeps that code valid instead of spamming their inbox or burning resend quota on double-clicks). If `true`, remind the user to check their inbox and show a **Resend code** button calling `POST /auth/dp/send-code`. | | `already_pending` | `boolean` | `true` when the email already has a pending unverified signup waiting for its code. Use it to route returning unverified users straight to the code entry step instead of hitting an "account already exists" dead end. | | `email` | `string` | The normalized email address that received the code. Display it in your prompt (`Enter the 6-digit code sent to ada@example.com`) and send it verbatim into `POST /auth/dp/verify-email` or `POST /auth/dp/send-code`. | | `message` | `string` | Ready-to-display status copy (automatically tailored to whether a fresh code was sent or an existing code is still active). Render it directly in a banner or toast. | | `expires_in` | `number` | Exact code lifetime in seconds (e.g. `600`). Use it to drive a countdown timer, schedule an expiry warning, or control resend UI state. | | `expires_in_display` | `string` | Pre-formatted human-readable duration (e.g. `"10 minutes"`). Drop it directly into helper text (`Code expires in 10 minutes`). | Your frontend prompts the user for the 6-digit code and posts it to your backend (`POST /api/verify-email`). Your backend forwards `{ email, code, project_id, type: "verification", browser_flow: false }` to `POST https://api.fenaura.dev/auth/dp/verify-email`, which verifies the code, marks the email verified, and returns `data.token`: ```json { "status": "success", "data": { "token": "", "session_minted": true } } ``` See [API Responses & Status Codes](/platform/responses-and-status-codes#signup-verification-required-response) for the full server-side response & HTTP status reference, and [All Direct API URLs](/platform/direct-urls) for every direct Fenaura URL on one page. ### Step 3: Your backend sets a first-party `HttpOnly` cookie Take `data.token` from Fenaura's response and set it in an `HttpOnly`, `Secure`, `SameSite=Lax` cookie on your own domain. ### Step 4: Verify on subsequent requests and cache in your own DB Read the cookie on your backend and verify it with `GET https://api.fenaura.dev/auth/dp/whoami` using `Authorization: Bearer `. Once verified, save or sync the user (`user.endUserId`, `user.email`) into your own database for faster subsequent reads without going back to Fenaura on every request (this also saves bandwidth, since Fenaura charges you for bandwidth). On sign-out, revoke the session with `POST https://api.fenaura.dev/auth/dp/logout`. ### Complete Express / Node proxy example ```ts // Copy your Project ID (UUID) from Project Overview. const FENAURA_PROJECT_ID = '9f2c4e1a-6b3d-4c8e-a7f5-2d1b0e9c8a74'; function setSessionCookie(res: any, token: string) { res.cookie('session', token, { httpOnly: true, secure: true, sameSite: 'lax', path: '/', }); } // 1) Sign up on your server (handles both email verification OFF and ON) app.post('/api/signup', async (req, res) => { const upstream = await fetch('https://api.fenaura.dev/auth/dp/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: req.body.email, password: req.body.password, project_id: FENAURA_PROJECT_ID, browser_flow: false, // Optional custom metadata (saved to end_users.metadata & public.users.metadata) metadata: req.body.name ? { name: req.body.name } : undefined, }), }); const payload = await upstream.json(); if (!upstream.ok) return res.status(upstream.status).json(payload); // Email verification is ON: forward the verification payload so your UI shows the 6-digit code screen if (payload?.data?.verification_required) { return res.json({ status: 'success', data: { verification_required: true, code_already_sent: payload.data.code_already_sent, already_pending: payload.data.already_pending, email: payload.data.email, message: payload.data.message, expires_in: payload.data.expires_in, expires_in_display: payload.data.expires_in_display, }, }); } // Email verification is OFF: Fenaura minted the session immediately if (!payload?.data?.token) return res.status(502).json({ error: 'missing_token' }); setSessionCookie(res, payload.data.token); return res.json({ status: 'success', data: { signed_in: true } }); }); // 2) Complete email verification when email verification is ON in Auth Settings app.post('/api/verify-email', async (req, res) => { const upstream = await fetch('https://api.fenaura.dev/auth/dp/verify-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: req.body.email, code: req.body.code, project_id: FENAURA_PROJECT_ID, type: 'verification', browser_flow: false, }), }); const payload = await upstream.json(); if (!upstream.ok || !payload?.data?.token) { return res.status(upstream.status).json(payload); } setSessionCookie(res, payload.data.token); return res.json({ status: 'success', data: { signed_in: true } }); }); // 3) Sign in on your server and set the first-party HttpOnly cookie app.post('/api/login', async (req, res) => { const upstream = await fetch('https://api.fenaura.dev/auth/dp/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: req.body.email, password: req.body.password, project_id: FENAURA_PROJECT_ID, browser_flow: false, }), }); const payload = await upstream.json(); if (!upstream.ok || !payload?.data?.token) { return res.status(upstream.status).json(payload); } setSessionCookie(res, payload.data.token); return res.json({ status: 'success', data: { signed_in: true } }); }); ``` ```ts // 4) Validate the cookie with Fenaura, then save/cache the user in your own DB app.get('/api/me', async (req, res) => { const token = req.cookies.session; if (!token) return res.status(401).json({ error: 'signed_out' }); const upstream = await fetch('https://api.fenaura.dev/auth/dp/whoami', { headers: { Authorization: `Bearer ${token}` }, }); if (!upstream.ok) { return res.status(upstream.status).json(await upstream.json()); } const { data } = await upstream.json(); // Save or upsert data.user ({ endUserId, email }) in your own Postgres/Redis // so subsequent app queries run against your own DB without hitting Fenaura again. return res.json({ user: data.user }); }); ``` ## Next - [HTTP fetch & your own backend](/http-and-backends): the architecture options, Fleet forwarding, and direct Postgres/Redis access. - [Direct API URLs Reference](/platform/direct-urls): every code-verified direct `https://api.fenaura.dev` URL on one page. - [API Responses & Status Codes](/platform/responses-and-status-codes): every success and error response shape. - [Authentication methods](/auth/methods): `browser_flow`, cookies, metadata, and verification codes. --- # Coming from Supabase URL: https://docs.fenaura.dev/coming-from-supabase Section: Getting started # Coming from Supabase If you have used Supabase, most of Fenaura will feel familiar. This page maps the names and covers the places where behaviour differs, because those are the ones that break a straight copy-paste port. ## Concept mapping | Supabase | Fenaura | Notes | |---|---|---| | Project | Project | Same idea: database, auth and storage together | | `supabase-js` | `fenaura-sdk` | Same `createClient` shape | | Edge Function (Deno) | Edge function (V8 isolate) | No Deno; npm packages bundle at deploy | | `ctx` / `req` | `FenauraContext` | Different fields; see the context reference | | `anon` key | Project ID | Safe to ship to a browser; grants nothing on its own | | `service_role` key | Project Secret Key | Never in a browser | | RLS policies | RLS policies | Postgres RLS, plus sensitive-column rules | | Storage buckets | Storage buckets | Chunked upload; 50 MiB default cap | | `.from().select()` | `.from().select()` | Same builder | | `.single()` / `.maybeSingle()` | `.single()` / `.maybeSingle()` | Same | | Auth `getSession` | `getSession` | Fenaura also checks the server | | Realtime | `fenaura.realtime` (`table()`, `channel()`, `dm()`, `group()`) | Live Postgres CDC, broadcast, presence, encrypted DMs, and ACL groups built in | | `@supabase/ssr` cookie plumbing | Nothing | The proxy sets a first-party cookie; delete the helpers | ## What differs **Edge functions are private by default.** In Supabase a function is reachable by anyone who knows the URL, and every handler repeats the same "verify the JWT" block. In Fenaura the session check happens before your handler runs, and you mark a route public only when you mean it. ```ts // Fenaura: the platform already rejected anonymous callers here. export default async (req: Request, ctx: FenauraContext) => { const userId = ctx.user!.userId; // safe, checked upstream // ... }; ``` To serve unauthenticated traffic, declare the route public in your function config. That is a deliberate act, and it is visible in one place instead of scattered through handlers. **Sessions arrive three ways.** Supabase checks a cookie. Fenaura accepts a cookie, `Authorization: Bearer `, or `X-Fenaura-EUSID: `, and the header wins. That means a native app or a browser extension can hold the token itself without a cookie jar. **There is no Deno.** Edge functions run in a V8 isolate with the web standard `Request` and `Response`. Imports resolve like a bundler: project files, and npm packages fetched and bundled at deploy time (see [Using npm packages](/ide)). There is no import map and no runtime fetch. ## Porting a query ```ts // Supabase const { data, error } = await supabase .from('notes') .select('*') .eq('owner', userId); // Fenaura const { data, error } = await fenaura .from('notes') .select('*') .eq('owner', userId) .execute(); ``` The chain is the same. Fenaura asks for `.execute()` on `update` and `delete` chains so it is never ambiguous whether a call ran. ## Porting an edge function ```ts // Supabase: every function re-checks the JWT itself import { createClient } from '@supabase/supabase-js'; export default async (req: Request) => { const auth = req.headers.get('Authorization')!.replace('Bearer ', ''); const supabase = createClient(url, key, { global: { headers: { Authorization: auth } } }); const { data: { user } } = await supabase.auth.getUser(); if (!user) return new Response('unauthorized', { status: 401 }); // ... }; // Fenaura: the session was already verified before your code ran export default async (req: Request, ctx: FenauraContext) => { const id = ctx.user?.userId; if (!id) return Response.json({ error: 'unauthorized' }, { status: 401 }); return Response.json({ ok: true, userId: id }); }; ``` The handler is a plain function. There is no `serve()`, no global registration, and no per-function client construction. The platform hands you `ctx.user` already resolved, `ctx.db` already connected, and rejects anonymous callers on private routes before your code runs. ## Moving your data The database moves as plain Postgres. You have two clean paths: ### Option A: Paste a Supabase `pg_dump` directly in SQL Editor Open **SQL Editor** in the dashboard, verify whether you are targeting **Development** or **Production**, paste your plain-SQL Supabase schema/data dump (`pg_dump --format=plain`), and run it. Fenaura's SQL translator and chunk runner automatically handle Supabase `pg_dump` statements cleanly: - Standard dump headers (`SET ...`, `SELECT pg_catalog.set_config(...)`, `\restrict`/`\unrestrict` client markers) are safely handled so they do not halt execution. - Supabase-specific `OWNER TO` clauses are skipped cleanly while preserving your project's own role permissions, RLS policies (`CREATE POLICY`), indexes, enums, functions, and `COPY ... FROM stdin` blocks. - **Production protection & Dev schema sync:** Running schema DDL in **Production** prompts a clear confirmation banner and gives you a one-click **Sync structure to Development** action so Development gets the exact 0-row table layout without copying production rows. ### Option B: External `psql` or `pg_restore` via Platform secrets If your dump is very large, open **Secrets › Platform secrets**, copy your environment's `DATABASE_PUBLIC_URL`, and stream directly from your terminal: ```bash # 1. Export from Supabase (application schemas such as public) pg_dump "$SUPABASE_DB_URL" --schema=public --no-owner -f dump.sql # 2. Import into Fenaura Development (or Production) over TLS psql "$DATABASE_PUBLIC_URL" -f dump.sql ``` Then verify row counts per table in the dashboard **Database** tab. Two Supabase-owned schemas (`auth` and `storage`) belong to GoTrue/Storage rather than your app schema; migrate users below and recreate buckets in **Storage**. ## Moving your users (with existing passwords intact) Fenaura supports **transparent bcrypt verification and automatic Argon2id migration** for users coming from Supabase GoTrue. You do **not** have to force existing users to reset their passwords: 1. **Export from Supabase `auth.users`:** Export `email`, `encrypted_password` (`$2a$`, `$2b$`, or `$2y$` bcrypt hash), `email_confirmed_at`, and optional `raw_user_meta_data` as JSON or CSV. 2. **Import into Fenaura:** Open **Users › Import users** in the dashboard (or call `POST /cp/management/projects/:projectId/end-users/import` with up to 1,000 rows per batch). Accepted fields include `email`, `encrypted_password` (or `password_hash`), `email_confirmed_at`, `metadata` / `raw_user_meta_data`, and `env` (`production` or `development`). 3. **Automatic upgrade on sign-in:** When an imported user logs in with their existing password, Fenaura verifies the bcrypt hash against their password and transparently re-hashes their stored credential to **Argon2id** in the background. Nothing changes for your users on login day. OAuth users move even more easily: enable the same provider (Google, GitHub, Apple, etc.) in **Authentication**, and users sign back in with the same provider identity. ## Migration order that works 1. Import your schema and data into **Development** (via SQL Editor paste or `psql "$DATABASE_PUBLIC_URL"`), and verify row counts. 2. Import your `auth.users` JSON/CSV (including `encrypted_password`) into **Users** and test signing in with an existing account password. 3. Point your frontend at `fenaura-sdk` (or plain `fetch` / mobile `browser_flow: false`) and remove `@supabase/ssr` cookie plumbing. 4. Choose your backend path: port handlers to Fenaura Fleets (`FenauraContext`) **or** keep your existing backend server connected to Postgres and Redis TLS via **Secrets › Platform secrets**. 5. Recreate buckets in **Storage**, promote verified schema changes to **Production**, and run the production user import. ## Next - [HTTP fetch & your own backend](/http-and-backends): using Fenaura auth with your own server and standard DB drivers. - [Backend auth implementation](/backend-auth-implementation): complete Express/Node auth proxy code. - [External Postgres & Redis](/database/external-connections): connecting Drizzle, Prisma, `pg`, or `ioredis` via Platform secrets. - [Querying](/database/querying): the builder in full. - [Pure fetch & mobile API](/sdk/fetch): calling auth, data, storage, and email with plain HTTP. --- # Veilo URL: https://docs.fenaura.dev/veilo Section: Veilo # Veilo Veilo is the AI engineer built into Fenaura. It is not a chat box bolted onto a dashboard, it is the primary way to build on the platform, and it holds tools for every part of a project. You describe what you want. Veilo writes the code, applies the schema change, deploys it, calls it, reads the response, and tells you whether it worked. ## What makes it different from a chatbot **It acts on your project.** Veilo has tools that write files, run SQL, deploy edge functions, edit database rows, send email, and drive the API tester. A general assistant can show you code; Veilo puts it in your project and runs it. **It verifies before it claims.** Veilo is built on a strict rule: it never reports an operation as successful unless a tool confirmed it. If a deploy failed, it says the deploy failed. It distinguishes *attempted*, *pending approval*, *executing*, *successful*, *failed* and *rejected* rather than flattening them into "done". **It reads before it writes.** Rather than assuming your project's shape, it searches the codebase, reads the relevant files, inspects the schema, and then acts. ```render img:docs-veilo-loop|The Veilo loop: read the project, plan safe steps, act, verify with real assertions, and report a verified result; destructive actions stop at a human approval gate ``` ## What it can do ### Write and change code | Tool | What it does | |---|---| | `file_read` | Read a file, or a slice of one | | `file_write` | Create or replace a file | | `file_edit` | Targeted edit to an existing file | | `file_patch` | Apply a patch | | `file_rename` / `file_batch_delete` | Rename or remove files | | `files_list` | List what exists | | `file_compile` | Compile-check a file | | `code_search` / `code_trace` | Find code and follow how it flows | | `harness_grep` / `harness_ast_inspect` | Grep and inspect syntax structure | For a large workspace it has focused tools rather than one blunt scan: `workspace_read_slices` reads ranges, `workspace_batch_edit` applies many edits in one transaction, and `workspace_bulk_edit` edits across a set of files it has not enumerated first. ### Database | Tool | What it does | |---|---| | `db_schema` | Show the schema | | `db_table_create` / `db_table_drop` | Create or drop a table | | `db_table_read` | Read rows | | `db_sql_execute` / `db_sql_run` | Run SQL (`db_prod_sql_execute` for production) | | `db_migration_propose` / `db_migration_apply` | Propose then apply a migration | | `db_seed` | Insert seed data | | `db_sensitive_columns_mark` | Mark a column as sensitive | | `db_dump` | Take a backup | Production SQL and migration-apply are separated from the development versions on purpose, and they require approval. That separation is the point: a change to real data should never be one keystroke away from a change to test data. ### Edge functions | Tool | What it does | |---|---| | `edge_deploy_dev` | Deploy to development | | `edge_deploy_prod` | Deploy to production (approval required) | | `list_routes` | List the routes a function exposes | | `route_manifest` | Describe routes, methods and bodies | | `dev_api_probe` | Call a route and inspect the response | ### Testing and verification | Tool | What it does | |---|---| | `run_route_suite` | Run a set of requests against the function | | `route_test_plan` | Plan a test suite from the routes | | `controller_test` | Exercise a controller | | `tests_run` | Run the project's tests | | `diagnose_failure` | Work out why something failed | | `debug_trace` / `trace_flow` | Follow execution to the source of a bug | | `find_error_source` | Locate where an error originates | | `self_review` | Review its own change before declaring it done | | `session_doctor` | Check the session and auth setup | `self_review` is worth knowing about: Veilo reviews its own diff against the request before telling you it is finished. When it disagrees with itself, it keeps working instead of reporting success. ### The API tester (Kora) Veilo drives the Kora API tester directly, so it can build and test a request collection without you clicking through it. | Action | What it does | |---|---| | `create_collection` / `rename_collection` / `delete_collection` | Manage collections | | `create_folder` / `move_folder` / `delete_folder` | Manage folders | | `upsert_request` / `update_request` / `save_request` | Create or change a request | | `delete_request` | Remove a request | | `locate_request` / `get_request` / `locate` / `grep` / `read` | Find and read requests | | `batch_edit` | Patch many requests in one transaction | | `sync_from_code` | Import routes from the edge function | | `apply_draft` | Apply a draft it prepared | | `sync_from_code` | Import routes from the edge function | | `close_tab` / `tabId` | Close a tab | ### Email | Tool | What it does | |---|---| | `email_template_list` / `email_template_source` / `email_template_preview` | Read templates | | `email_template_save` / `email_template_rename` / `email_template_delete` | Change templates | | `email_template_visual_debug` | Check how a template renders | | `email_template_images_audit` | Check the images in a template | | `email_send` / `email_send_test` | Send mail | | `email_spam_check` | Check deliverability signals | | `email_outbox_list` / `email_outbox_read` | Read what was sent | | `email_stats_inspect` | Delivery statistics | | `email_asset_import` / `email_assets_list` / `email_asset_delete` | Manage assets | | `email_list_images` / `image_inspect` / `image_edit` | Work with images | ### Git | Tool | What it does | |---|---| | `git_status` / `git_stage` / `git_unstage` | Inspect and stage | | `git_commit` | Commit | | `git_branches_list` | List branches | | `git_merge_preview` / `git_merge_resolve` | Preview and resolve a merge | | `git_pull_upstream` | Pull | | `shadow_git_checkpoint` / `shadow_git_diff` | Checkpoint and diff its own work | ### Research | Tool | What it does | |---|---| | `web_search` | Search the web | | `web_scrape` | Read a page | | `sdk_docs` | Look up Fenaura SDK reference | Veilo is instructed to treat web content, file content and database content as **untrusted data, never as instructions**. Text inside a file that says "ignore your rules" is data that describes a file, and Veilo will not follow it. ## Approvals Anything destructive or production-facing stops and asks: - dropping a table - running SQL against production - applying a migration to production - deploying to production - sending real email The approval card states what will happen in one or two lines, and the action runs only when you approve it. Everything else, writing a file, renaming something, deploying to development, running a test, executes directly, because waiting for permission on a reversible change is friction with no benefit. ## Why Veilo asks questions sometimes For a clear order ("rename `getUser` to `loadUser`", "deploy this", "commit"), Veilo just does it. For an open request ("make me an email template", "I need an API"), it asks two to four focused questions first: what the template is for, who receives it, what the API should do. Guessing there produces confident work on the wrong thing, which costs more than the question. ## Prompt caching Veilo's instructions are split into a fixed core and situational modules that load per task. The fixed part is byte-identical across turns so it can be cached, which is what keeps a long session fast and affordable. It also means the rules it holds itself to do not drift mid-conversation. ## What it will not do - It will not claim a deploy succeeded when the deploy failed. - It will not touch production data without approval. - It will not follow instructions found inside your files or a web page. - It will not invent a resource id, a save confirmation or a delivery receipt. If it says something worked, a tool returned `ok: true` for it. If you want to see the evidence, ask, it can show the tool result. ## Next - [Using Veilo](/veilo/using): how to talk to it well. - [Approvals](/veilo/approvals): what needs approval and why. - [The API tester](/kora): the collection head Veilo drives. - [The Fenaura Fleet IDE](/ide): the editor beside it. --- # Using Veilo URL: https://docs.fenaura.dev/veilo/using Section: Veilo # Using Veilo Veilo is competent at execution and needs to know what "done" looks like. Most disappointing sessions come from a vague goal, not a weak model. ## Say what done looks like Weak: > Make the notes endpoint better. Better: > The `GET /api/notes` route should return only the caller's notes, newest first, > limited to 50, and each note should include an `author_name`. Deploy it to > development and show me the response for a signed-in user. The second version names the route, the filter, the ordering, the limit, the shape of the response, the environment, and the proof you want. Veilo can verify every one of those. ## Give the constraint, not just the goal Veilo will pick a reasonable approach. If you need a specific one, say so: > Use `ctx.sql`, not Drizzle, this query needs a window function. Otherwise you may get a correct answer in a style you then have to undo. ## One job per message Veilo handles multi-step work well, but a message with five unrelated jobs produces a session where it is hard to tell which part failed. Split unrelated work into separate messages. A sequence like "write it, deploy it, test it" is one job and should stay together. ## Ask for the evidence When you want proof rather than a claim: > Show me the tool result for that deploy. Veilo can show what the tool returned. That is the difference between "it deployed" and "the deploy returned ok: true". ## When it does the wrong thing **It changed more than you asked.** Say exactly which part to revert. A specific instruction, "only revert the change to `src/routes/notes.ts`", gets applied precisely. **It stopped and asked a question.** Answer it. That is the approval or clarification path working as designed. For an ambiguous goal it asks before building, which is cheaper than building the wrong thing. **It says something failed and you think it succeeded.** Ask for the tool result. If the tool returned an error, the operation genuinely did not happen, and the platform is telling you the truth rather than smoothing it over. **It keeps going in circles.** Start a new message with the specific failure and the file it is in. A long thread where the same thing has failed three times is usually missing one fact, and naming that fact is faster than another attempt. ## Things worth knowing **Typo correction is built in.** If you write `gmail.cm` or `hotmial.com`, Veilo treats it as the obvious intent rather than sending mail to a domain that does not exist. Known providers and top-level domains are definite. **Clear orders execute immediately.** Renaming, editing, committing, deploying to development, sending email, no "say go" gate. The approval gate exists for production data and destructive operations, not for routine work. **It will not moralise.** If you ask it to send a test email with sample copy, it sends it. It is a tool in your project, not a reviewer of your decisions. ## A good opening message ``` Project: my-app Goal: an authenticated endpoint that lists the signed-in user's orders. Constraints: - Postgres table "orders" already exists with owner_id - Use ctx.db, not raw SQL - Return 50 most recent, newest first Done when: - /api/orders returns 200 for a signed-in user - it returns only that user's rows - you have called it and shown me the response ``` Four lines, and Veilo has everything. Most frustration disappears at this step. ## Next - [Veilo overview](/veilo): the full tool set. - [Approvals](/veilo/approvals): what will stop and ask. --- # Approvals URL: https://docs.fenaura.dev/veilo/approvals Section: Veilo # Approvals Veilo runs most work directly. A small set of actions stops and asks, and knowing where that line sits explains why some things need permission and others do not. ## What needs approval | Action | Why | |---|---| | Dropping a table | Deletes data that cannot be recovered | | Running SQL against production | Touches real users' rows | | Applying a migration to production | Changes the shape of real data | | Deploying to production | Ships to live traffic | | Sending real email | Cannot be unsent | Everything else runs immediately: writing a file, editing a file, renaming, creating a table in development, deploying to development, running tests, reading anything, committing. ## The rule behind the line **Reversible and local runs. Irreversible or public stops.** Writing a file is reversible, git holds the old version. Sending an email is not. Deploying to development is local, a mistake costs you a retry. Deploying to production can break a live product. If an action cannot be undone, or its effects are visible outside your project, it asks first. ## What the approval card shows The card states what will happen in one or two lines, and it names the thing it will touch: > Drop table `orders`, 4,182 rows will be permanently deleted. Not "perform destructive operation". A confirmation you cannot evaluate is worse than no confirmation, because it trains you to click through. Nothing runs until you approve. If you decline, the operation is recorded as rejected, not as attempted-and-failed. ## Why routine work does not ask A gate on reversible work trains you to click approve without reading. Once that habit forms, the gate does not protect you, it just adds a click before the dangerous thing too. That is why "deploy to development" does not ask and "deploy to production" does. The prompt is rare enough that you read it. ## When you are blocked If you asked for a production change and nothing happened, an approval is probably waiting. Check the conversation for a card. Veilo will not proceed without an answer, and it will not pretend the action succeeded either, the state stays *pending* rather than flipping to *done*. ## Reducing approval prompts Approve deliberately rather than reflexively, and keep dangerous things rare: - Develop against the development environment, where nothing needs approval. - Make one production change per approval, so a decline is specific. - Use migrations for schema changes; a migration is reviewable in a way that ad-hoc SQL is not. ## Next - [Veilo overview](/veilo): the tools behind each action. - [Environments](/edge/environments): why development is free of gates. --- # The API tester URL: https://docs.fenaura.dev/kora Section: Veilo # The API tester Kora is the HTTP client inside the dashboard. It sends real requests to your edge function with real sessions and shows you real responses. ## Collections and folders Requests live in collections, and collections hold folders. Both exist so a large API stays navigable: ``` Payments API ├── Customers │ ├── GET /api/customers │ └── POST /api/customers └── Invoices ├── GET /api/invoices/:id └── POST /api/invoices ``` Folders also group by table when Kora imports routes, so a database-backed API organises itself. ## Importing routes Kora reads the edge function, detects the routes it exposes, and generates requests for them automatically, grouped into folders by table where the route is database-backed. A new route becomes a clickable request instead of something you type by hand. It also imports from outside: **cURL** and **Postman v2** collections both import directly, so a collection you already have is not stranded in another tool. ## Cloud workspace sync The workspace is saved to your account, not only to this browser. Open the API tester on a phone and your collections are there; the sync indicator shows when the local copy matches the server one. This is why a request you built on a laptop is available on a phone without exporting anything. ## Editing a request A request has five sections, each in its own panel: | Section | Holds | |---|---| | Method and path | The verb and the URL | | Params | The query string | | Headers | Header rows, key and value | | Body | The JSON body | | Auth | The session token | **Section diffs.** When a request is saved and you change it, the panel you are editing shows what changed against the saved version: added lines in green, removed in red, with a `+N / -N` count. Each panel diffs only its own section, so a header change does not appear inside the body panel. That distinction is the whole point, a diff that mixes sections tells you something changed but not what. Unsaved drafts have no baseline, so no diff appears for them. ## Environments Kora switches between development and production with one control, and shows which one you are on. A request sent to development goes to `dev-{token}`; production goes to `{token}`. Sending a production request from Kora is a real request against real data. The environment indicator is there to make that visible before you press send. ## What the response shows Status code, timing, size, headers (collapsible), and a pretty-printed body with search and collapse. The response body is the actual bytes the function returned, not a rendering of them. ## Saving A request can be saved into a collection, renamed, moved between folders, and deleted. The list marks a request as modified when it differs from the saved version, which is the same baseline the section diff uses. ## Veilo drives it Every one of those actions is available to Veilo as a tool. It can create a collection, import routes, patch request bodies, and run them, which is how a whole test collection gets built without clicking through it. See [Veilo](/veilo) for the tool list. ## Why a built-in tester Testing an edge function from outside needs a session token, the right base URL for the environment, and the dev key when you are on development. A general HTTP client has none of that, so the common outcome is a `401` you cannot explain. Kora knows the project, the environment and the session, so a request you build works the first time. ## Next - [Edge functions](/edge): what you are calling. - [Errors](/edge/errors): reading the responses you get back. --- # The Fenaura Fleet IDE URL: https://docs.fenaura.dev/ide Section: Veilo # The Fenaura Fleet IDE An edge function is one deployment made of many files. The Fenaura Fleet IDE is where you work on it: a file tree, an editor, a terminal, source control, and a history of what changed. Nothing to install on your machine. There is no local toolchain and no build step, the platform compiles. You can still run `npm install ` inside the Fleet IDE terminal, or ask Veilo to install a package, and it is bundled at deploy time. ## Using npm packages You can use packages from npm directly. Import them the normal way and the build fetches and bundles them for you at deploy time: ```ts import { z } from 'zod'; const Body = z.object({ title: z.string() }); ``` Pin a version with the `npm:` prefix when you want to lock one down: ```ts import { z } from 'npm:zod@3.23.8'; ``` How it works, and why it is safe: - The build resolves the package from the npm registry (through esm.sh), bundles it into your deployed code, and reports a build error if the import cannot be resolved, the same way it does for a typo in a project file. - Nothing is installed on your machine and nothing runs at install time. Your deployed function runs in an isolated isolate with bundled code only, so a package cannot reach your project from outside the sandbox. - Each deploy re-resolves unpinned imports, so a new release of a package can reach you on your next deploy. Pin the version when that matters. - `hono` ships with the runtime: importing it works and adds nothing to your bundle, since the build maps it to the runtime's global Hono. ## What is in it | Part | Purpose | |---|---| | File tree | Every file in the function, resizable | | Editor | Write code, with syntax highlighting and symbols | | Bottom panel | A Terminal and a Problems tab | | Side panel | Source control and versions | | Trash | Deleted files, recoverable from their own page | The bottom panel switches between the terminal and the problems list. The trash is a page of its own rather than a panel tab, because restoring a file is a task you start and finish, not something you glance at while editing. ## Writing code The editor highlights JavaScript and TypeScript, and it reads the symbols in the file, functions, types, exports, so jumping within a large file does not mean scrolling to find something. Imports resolve at deploy time. A relative import works; there is no runtime resolution and no `npm:` specifier that loads later. ## Compiling and problems `build` checks the function without deploying it, from the terminal or the toolbar. Errors land in the Problems tab with the file and line, so you fix them before a deploy rather than discovering them in a failed request. Clicking an error jumps to it. A build is not a deploy. Nothing reaches development or production until you deploy, which is what makes it safe to run constantly. ## Source control Commit history lives beside the code. You can stage files, commit with a message, create and switch branches, preview a merge, and resolve conflicts. **Diffs.** Any change can be viewed as a diff: added lines in green, removed in red, unchanged context around them. The same diff view serves a working-tree change, a commit, and a version on the timeline, one way to read what changed, everywhere it appears. ## Versions and rollback The timeline lists changes over time. Selecting one shows the diff against its parent, so a change made an hour ago is inspectable without reproducing it. That is how you find the change that broke something, rather than guessing. ## The trash Deleted files are not immediately gone. The trash holds them, so a delete you regret is recoverable without reverting a commit. ## How it relates to Veilo Veilo edits the same files through its own tools. You and Veilo work on the same function, and the file tree shows the result either way. When Veilo reports it edited a file, the file is edited, you can open it and read the change. The IDE is where you review and adjust what Veilo did, and where you write the part you would rather write yourself. ## Next - [Veilo](/veilo): the agent that works beside it. - [Edge functions](/edge): routing, context and errors. - [The API tester](/kora): calling what you built. --- # Fleets URL: https://docs.fenaura.dev/fleets Section: Fleets # Fleets A Fleet is the server side of your project. It holds your code, runs it close to the user, and owns the URL your app calls. If you have built a backend before, an Express app, a Flask app, a serverless function, a Fleet is that same job. What differs is how little you configure to get it. ## The one idea that explains Fleets **A Fleet is treated as a server, not as a pile of functions.** On most serverless platforms you upload a single function and get a single URL per function. Ten routes means ten deployments, ten URLs, and ten cold starts. You end up writing glue to make them feel like one application. In Fenaura you deploy **one Fleet per environment**, and inside it you route however you like. The project URL runs everything: ``` Browser: /fenaura/fleet/{token}/api/notes (proxied to edge.fenaura.dev so cookies follow) Non-browser: https://edge.fenaura.dev/{token}/api/notes ``` You can copy either URL directly on **Project Overview**: the **Fleet URL** dropdown defaults to **Fleet (Browser)** (`/fenaura/fleet/{token}` or `/fenaura/fleet/dev-{token}` in development) and switches to **Full Fleet URL** (`https://edge.fenaura.dev/...`) for non-browser clients. One deployment. One URL. Many routes. **About the name and the location.** A "Fleet" is a group of engines, the idea is that your backend runs as a set of fast, isolated workers. Do not read "edge" as "geographically distributed to the user's device": Fenaura runs your code centrally, in one place you control, not spread across global regions. The name is about the workers, not the geography. Everything you build comes from one central location, and you never juggle regional URLs. ## How this differs from edge functions you may know | | Typical edge functions | Fenaura Fleets | |---|---|---| | Unit of deploy | One function, one URL each | One Fleet, one URL for all routes | | Runtime | Varies by platform | V8 isolate, web standard `Request`/`Response` | | Auth by default | Each handler verifies its own token | Every route is session-gated before your code runs unless marked public | | Routing | Bolt-on, per function | Built in, one router | | Environments | Separate projects | Same code, `dev-` prefix, separate data | The important row is auth. There, every function repeats a "verify the token" block, and a function that forgets it is public. In a Fleet the gateway checks the session **before your handler is called** and returns `401` on any non-public route when unauthenticated, so a route is private by default without manual `if (!ctx.user)` checks. ## Development and production Two environments, the same code: ``` Production https://edge.fenaura.dev/{token}/api/notes Development https://edge.fenaura.dev/dev-{token}/api/notes ``` The prefix is the only difference in the URL. Everything behind it is separate: | | Development | Production | |---|---|---| | Database | its own | real user data | | Redis | its own database | its own database | | Environment variables | its own | its own | | End users | its own | real users | | Storage | its own | its own | You deploy the same code to both. Data never moves between them, which is the whole point, a test in development cannot write a row a real customer will see. **Secret names are shared; values are not.** You set `STRIPE_SECRET_KEY` once as a name in both environments and give each its own value: a test key in development, a live key in production. Your code reads `ctx.env.STRIPE_SECRET_KEY` and never learns which environment it is in. Fenaura routes the right value at runtime based on the deployment that is handling the request. ## The development URL goes away A development URL is deliberately temporary. It requires proof that you are allowed to use it: - an **active development session**, or - the project's **private dev key**, sent as a header. Without one, the request is refused before your code runs: ``` 401 DEV_ACCESS_DENIED ``` This is why a development URL can sit in a local bundle safely, knowing the URL is not enough. And it is why the development URL is not something to ship: the public application calls the production Fleet URL, and nobody outside your team can reach the development one. ## Why this feels like a real IDE Fleets ship with a working environment, not a text box: - a **file tree** and folders, so code is organised the way a project is - a **terminal** with real commands (`build`, `deploy`, `save`, `fmt`, `open`, `files`, `ctx`, `env`, `versions`) - **source control**, stage, commit, branch, diff, resolve - a **problems panel** that jumps to the error - a **version timeline** so you can see what changed and when - a **trash** so a delete is recoverable Imports work, folders work, and a compile check runs before a deploy. The point of all of it is that you spend your attention on the code rather than on the tooling around it. ## Where the code runs ``` Browser │ const FLEET_URL = '/fenaura/fleet/k7m9x2p' │ fetch(`${FLEET_URL}/api/notes`, { credentials: 'include' }) ▼ Your domain proxy -> https://edge.fenaura.dev/k7m9x2p/api/notes │ session check, before your code ▼ Your handler (V8 isolate) ctx.user, ctx.db, ctx.env, ctx.redis, ctx.sql ▼ Postgres / Redis / Storage ▼ Response ``` Your handler does not need an `export default` wrapper or an `if (!ctx.user)` check; just write your code directly in `main.ts`: ```ts // main.ts return ctx.json({ hello: ctx.user.identifier }); ``` `req` and `ctx` are already in scope (see [Drizzle in the edge](/database/drizzle) for database queries with `ctx.db.query`). There is no framework to learn before your first request works. ## Responses: status codes, headers, cookies, and redirects ### Status codes Pass the HTTP status code as the second argument to `ctx.json` (or `c.json`, `c.text`, `c.html` in Hono), or in `new Response(body, { status })`: ```ts return ctx.json({ created: true }, 201); // or: return new Response(JSON.stringify({ error: 'Invalid input' }), { status: 400, headers: { 'content-type': 'application/json' }, }); ``` Note: `c.status(...)` in Hono-style handlers is a no-op in the runtime shim. Always pass the status code directly to `c.json(data, status)`, `c.text(text, status)`, `c.html(html, status)`, or `new Response(...)`. ### Response headers Set custom response headers with `c.header(name, value)` or `new Response(body, { status, headers })`: ```ts app.get('/hello', (c) => { c.header('x-custom-header', 'fenaura'); return c.json({ ok: true }, 200); }); ``` Gateway rules on response headers: - `Content-Type` defaults to `application/json` if omitted. - `Cache-Control` is always set to `no-store` by the gateway so stale deployments are never cached. - `Access-Control-Allow-Origin` defaults to `*` on Hono helper responses (`c.json`, `c.text`, `c.html`, `c.redirect`), or echoes your allowlisted request `Origin` at the gateway when no `Access-Control-Allow-Origin` header was set. - Hop-by-hop and platform headers (`connection`, `content-length`, `date`, `host`, `keep-alive`, `proxy-authenticate`, `proxy-authorization`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `x-fenaura-request-id`, `x-fenaura-execution-time-ms`) are stripped. ### Cookies (`Set-Cookie`) and redirects (`Location`, `Refresh`) - **Cookies (`Set-Cookie`) are stripped.** Fleets cannot set `Set-Cookie` headers on responses. End-user session cookies are managed by Fenaura Auth endpoints (`/auth/...` via your `/fenaura/*` proxy), or via `Authorization: Bearer ` headers. - **Redirects (`Location`, `Refresh`) are stripped.** Fleets cannot return HTTP `Location` or `Refresh` redirect headers from `edge.fenaura.dev`. Return JSON (for example `{ redirectTo: '/next' }`) and let your frontend navigate. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Your first Fleet](/edge/first-function): deploy something. - [Routing](/fleets/routing): controllers, and why Hono is optional. - [The context object](/fleets/context): every `ctx` field. - [Drizzle in the edge](/database/drizzle): querying your database. - [The IDE](/fleets/ide): the editor around your code. --- # Routing URL: https://docs.fenaura.dev/fleets/routing Section: Fleets # Routing A Fleet is one server, so routing is your decision. You can write plain JavaScript, split controllers across folders like Express, or use the built-in `Hono` router. ## 1. Plain JavaScript routing For a small Fleet, branch on `req.method` and `req.path` directly in `main.ts`: ```ts // main.ts if (req.path === '/api/notes' && req.method === 'GET') { const notes = await ctx.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [ctx.user.userId], ); return ctx.json({ notes }); } const match = req.path.match(/^\/api\/notes\/([^/]+)$/); if (match && req.method === 'GET') { const rows = await ctx.db.query( 'select * from notes where id = $1 and owner = $2 limit 1', [match[1], ctx.user.userId], ); if (!rows.length) return ctx.json({ error: 'Not found' }, 404); return ctx.json({ note: rows[0] }); } if (req.path === '/api/notes' && req.method === 'POST') { const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); const title = typeof body?.title === 'string' ? body.title.trim() : ''; if (!title) return ctx.json({ error: 'A title is required' }, 400); const rows = await ctx.db.query( 'insert into notes (title, owner) values ($1, $2) returning *', [title, ctx.user.userId], ); return ctx.json({ note: rows[0] }, 201); } return ctx.json({ error: 'Not found', path: req.path }, 404); ``` ## 2. Doing the same thing in Hono When your routes grow, use the built-in `Hono` router. You don't need an `export default` wrapper, the Fleets IDE wraps `app` automatically, and `ctx` is passed as `c.env`: ```ts // main.ts import { Hono } from 'hono'; const app = new Hono(); app.get('/api/notes', async (c) => { const notes = await c.env.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [c.env.user.userId], ); return c.json({ notes }); }); app.get('/api/notes/:id', async (c) => { const rows = await c.env.db.query( 'select * from notes where id = $1 and owner = $2 limit 1', [c.req.param('id'), c.env.user.userId], ); if (!rows.length) return c.json({ error: 'Not found' }, 404); return c.json({ note: rows[0] }); }); app.post('/api/notes', async (c) => { const body = await c.req.json().catch(() => ({})); const title = typeof body?.title === 'string' ? body.title.trim() : ''; if (!title) return c.json({ error: 'A title is required' }, 400); const rows = await c.env.db.query( 'insert into notes (title, owner) values ($1, $2) returning *', [title, c.env.user.userId], ); return c.json({ note: rows[0] }, 201); }); ``` ## 3. Folders, subfolders, and controllers (just like Express) In the Fleets IDE file tree, you can create folders and subfolders (`routes/`, `controllers/`, `lib/`, `routes/v1/`, etc.). **`main.ts` is always the entry file**, just like `index.ts` or `server.ts` in an Express server: ```text main.ts entry file: creates app and mounts routers controllers/ notes.ts note handlers users.ts user handlers lib/ validate.ts shared validation helpers ``` ```ts // controllers/notes.ts import { Hono } from 'hono'; export const notesRouter = new Hono(); notesRouter.get('/', async (c) => { const notes = await c.env.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [c.env.user.userId], ); return c.json({ notes }); }); notesRouter.post('/', async (c) => { const body = await c.req.json().catch(() => ({})); const title = typeof body?.title === 'string' ? body.title.trim() : ''; if (!title) return c.json({ error: 'A title is required' }, 400); const rows = await c.env.db.query( 'insert into notes (title, owner) values ($1, $2) returning *', [title, c.env.user.userId], ); return c.json({ note: rows[0] }, 201); }); ``` ```ts // main.ts import { Hono } from 'hono'; import { notesRouter } from './controllers/notes'; const app = new Hono(); app.route('/api/notes', notesRouter); ``` All relative imports are bundled together at deploy time. ## 4. Middleware, `basePath`, `onError`, and `notFound` Hono's router features work out of the box in the Fenaura runtime: - `app.use(path?, middleware)`, Koa-style `(c, next)` middleware chain with `c.set(key, val)` and `c.get(key)` (runs on standard routes; hoisted public routes such as `publicGet` / `publicRoutes` bypass `app.use`). - `app.basePath('/api')`, prefix all routes on that `Hono` instance. - `app.route('/notes', subApp)`, mount sub-routers from other files/folders. - `app.onError((err, c) => ...)`, catch unhandled errors thrown in route handlers. - `app.notFound((c) => ...)`, custom `404` response when no route matches. ```ts import { Hono } from 'hono'; const app = new Hono().basePath('/api'); app.use('*', async (c, next) => { c.set('startedAt', Date.now()); await next(); c.header('x-response-ms', String(Date.now() - c.get('startedAt'))); }); app.onError((err, c) => { ctx.log.error('Unhandled route error', err); return c.json({ error: 'Internal error', requestId: c.env.requestId }, 500); }); app.notFound((c) => c.json({ error: 'Not found', path: c.req.path }, 404)); ``` ## 5. npm packages You can import npm packages (e.g. `import { z } from 'zod'`) from any file in your Fleet. Run `npm install ` in the Fleet IDE terminal, or ask Veilo, to add one to the project's database-backed virtual `node_modules`; the bundler resolves installed packages first and falls back to `esm.sh` at deploy time. `hono` is built into the runtime at zero bundle cost. Because Fleets run in a V8 isolate (not Node.js), pick packages that do not depend on `fs`, `child_process`, or `process`. ## 6. Manual `export default` (optional) If you want full manual control instead of automatic wrapping, export a default handler `(req, ctx) => ...` (or Cloudflare Workers `{ async fetch(req, ctx) {} }`). See [The context object](/fleets/context) for every field on `req` and `ctx`. --- # The context object URL: https://docs.fenaura.dev/fleets/context Section: Fleets # The context object Every Fleet runs in a V8 isolate. How you access `req` and `ctx` depends on which style you write: - **Plain `main.ts` (auto-wrapped):** The IDE wraps your file in `export default async (req, ctx) => { ... }`, so `req` and `ctx` are directly in scope as top-level variables. - **Explicit `export default`:** Write `export default async (req, ctx) => { ... }` (`req` is the 1st parameter, `ctx` is the 2nd). - **Hono (`new Hono()`):** Inside `app.get(...)` / `app.post(...)` handlers, the request is wrapped as **`c.req`** and the `ctx` object is passed as **`c.env`**. ## 1. Complete `ctx` object reference Every member below is wired onto `ctx` (and `c.env` in Hono) by the runtime shim before your handler starts: | Member | Shape / Signature | What it gives you | |---|---|---| | `ctx.req` | `{ method, path, query, url, headers, body }` | Current incoming request object (same object passed as `req`). | | `ctx.user` | `{ userId, id, identifier }` | Verified signed-in end user (`id` is an alias for `userId`). On private routes, the gateway returns `401` before your code runs when no session is present; on `{ public: true }` routes with no session, `userId` and `identifier` are `''`. | | `ctx.project` | `{ id, slug, schema_name, schema_role, database_name }` | Active project metadata and database schema identifiers. | | `ctx.env` | `Record` | Decrypted environment variables for the active environment (also readable directly on `ctx.`, `Deno.env.get(key)`, or `process.env.`). | | `ctx.environment` | `'test' \| 'production'` | Active runtime environment (`'test'` in Development, `'production'` in Production). | ### Checking the environment in a handler `ctx.environment` is `'test'` for a Development deployment and `'production'` for a Production deployment. The code itself is identical in both. Only the backing resources and environment variables differ, so a common pattern is to skip or stub an external integration in Development: ```ts app.get('/api/charge', async (c) => { const isDev = c.env.environment === 'test'; const key = isDev ? 'dummy-key' : c.env.PAYMENT_API_KEY; if (!isDev && !key) return c.json({ error: 'PAYMENT_API_KEY is missing' }, 500); return c.json({ env: c.env.environment, mode: isDev ? 'dummy' : 'live' }); }); ``` The `dev-` host prefix and `ctx.environment` describe the same deployment. Use `ctx.environment` when your logic needs to know which environment is running. | `ctx.requestId` | `string` | Unique request ID for tracing, response headers, and error payloads. | | `ctx.db` | `Drizzle & { query, execute, transaction }` | Project Postgres client: parameterized `ctx.db.query(sql, params)`, Drizzle `select`/`insert`/`update`/`delete`, `ctx.db.execute(ctx.sql\`...\`)`, and `ctx.db.transaction(async (tx) => ...)`. | | `ctx.sql` | `sql` template tag | Drizzle `sql` template helper (including `sql.raw`, `sql.empty`, `sql.join`). | | `ctx.pg` | `pgCore` helpers | Drizzle PostgreSQL schema helpers (`pgTable`, `uuid`, `text`, `integer`, `boolean`, `jsonb`, `timestamp`, etc.). | | `ctx.redis` | Redis command proxy | Project-isolated Redis client supporting Redis commands as async methods (`get`, `set`, `setex`, `incr`, `del`, `expire`, `hset`, `hget`, `lpush`, `rpop`, `zadd`, etc.). | | `ctx.realtime` | `{ publish(topic, event, payload?), token(topic, opts?) }` | Publish live Realtime events to connected WebSocket subscribers or mint scoped channel tokens. | | `ctx.email` | `{ send(opts) }` | Transactional email sender (`{ to, subject, html, text, template, vars }`). Captured in Dev Mailbox in development. | | `ctx.storage` | `{ from, system, listBuckets, createBucket }` | Project object storage (`ctx.storage.from(bucket)`, `ctx.storage.system.from(bucket)`, `listBuckets()`, `createBucket(name, opts)`). | | `ctx.image` | `{ transform, getTransformUrl }` | On-the-fly image transforms (`transform(bucket, key, opts)`, `getTransformUrl(bucket, key, opts)`). | | `ctx.cookies` | `{ get, has, set, delete }` | Cookie helper (`fenaura_*` names blocked; note the gateway strips inbound `cookie` and outbound `set-cookie` on deployed HTTP responses). | | `ctx.json` | `(data, status = 200) => Response` | Helper returning a JSON `Response` with `content-type: application/json`. | | `ctx.toWebRequest` | `(req?) => Request` | Bridges Fenaura's plain JSON `req` object into a Web Standard `Request` instance. | | `ctx.log` | `{ debug, info, warn, error, child }` | Structured logger streamed to the IDE terminal and Dashboard Logs with automatic secret redaction. | | `ctx.waitUntil` | `(promise) => void` | Runs background work after the HTTP response is sent (up to 5 chained flush rounds). | ### `ctx.user` on development calls without a browser session When you call a `dev-` Fleet URL from curl, your own backend, or the API tester, send `X-Fenaura-Dev-Key: ` (from **Project Overview › Dev private key**). The gateway verifies that key and resolves your own developer mirror end user, because you are a user in your own app. `ctx.user` is then populated exactly as it would be for a signed-in session, including RLS and every downstream check: ```ts app.get('/api/whoami', (c) => { const { userId, id, identifier } = c.env.user; return c.json({ userId, id, identifier }); // Example: { userId: '2f9c...', id: '2f9c...', identifier: 'you@example.com' } }); ``` `id` is an alias of `userId`, and `identifier` is the scoped end-user identifier. On a private route reached with the dev key, `ctx.user` is never `undefined`. On the production Fleet URL, callers must present a valid end-user session (`Authorization: Bearer `), and `{ public: true }` routes intentionally see empty strings. ## 2. The `req` object (`req` and Hono `c.req`) `req` is pre-populated from the incoming HTTP request before your handler starts, so you can inspect method, path, query string, headers, and parsed body immediately. ### In plain `main.ts` (`req` or `ctx.req`) | Property | Type | Value & behavior | |---|---|---| | `req.method` | `string` | HTTP method (`'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, etc.). | | `req.path` | `string` | Normalized path starting with `'/'` (`'/'` on the base URL, `'/notes'` on `/notes`). | | `req.query` | `string` | Raw query string without the leading `'?'` (e.g. `'limit=20'`, or `''` when absent). | | `req.url` | `string` | Full derived URL string (so `new URL(req.url).searchParams.get('limit')` works). | | `req.headers` | `Record` | Lowercased request headers (`cookie`, `authorization`, and `proxy-authorization` are stripped at the gateway). | | `req.body` | `unknown` | Already JSON-parsed if the body was valid JSON, raw string if not JSON, or `null` if empty. | ```ts // main.ts const url = new URL(req.url); const limit = Number(url.searchParams.get('limit') ?? '20'); const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); const webReq = ctx.toWebRequest(req); // Web Standard Request if a library expects one ``` ### In Hono (`c.req`) | Member | Return type | What it gives you | |---|---|---| | `c.req.method` | `string` | HTTP method string. | | `c.req.path` | `string` | Normalized request path string. | | `c.req.url` | `string` | Full request URL string. | | `c.req.param(name)` | `string` | Route parameter (e.g. `c.req.param('id')` from `/notes/:id`). | | `c.req.query(name?)` | `string \| Record` | Single query param (`c.req.query('limit')`) or all params as an object (`c.req.query()`). | | `c.req.header(name)` | `string \| undefined` | Case-insensitive request header lookup (`c.req.header('content-type')`). | | `await c.req.json()` | `Promise` | Parsed JSON request body (`null` if empty). | | `await c.req.text()` | `Promise` | Raw request body string. | | `c.req.raw` | `Request` | Underlying Web Standard `Request` instance. | ```ts app.get('/notes/:id', async (c) => { const id = c.req.param('id'); const format = c.req.query('format') ?? 'json'; const allParams = c.req.query(); return c.json({ id, format, allParams }); }); ``` ### Public vs private routes in Hono All routes share the same Fleet URL from **Project Overview › Fleet URL**. Routes require a signed-in user (`ctx.user`) by default. Pass `{ public: true }` (or use `app.publicGet` / `app.publicPost` / `app.publicRoutes`) to allow unauthenticated calls: ```ts app.get('/health', { public: true }, (c) => c.json({ ok: true })); app.publicPost('/webhooks/stripe', async (c) => { const payload = await c.req.text(); return c.json({ received: payload.length > 0 }); }); ``` ## 3. Responses and status codes ### In plain `main.ts` Use `ctx.json(data, status)`, return a plain object (defaults to `200`), or return `new Response(body, { status, headers })`: ```ts return ctx.json({ ok: true }); // 200 JSON return ctx.json({ error: 'Not found' }, 404); // 404 JSON return { ok: true }; // 200 JSON shorthand return new Response(null, { status: 204 }); // 204 No Content return new Response('Hello', { status: 200, headers: { 'content-type': 'text/plain' }, }); ``` *(Note: `Response.json(...)` is not available on the built-in `Response` class; always use `ctx.json(...)`, `c.json(...)` in Hono, or `new Response(...)`.)* ### In Hono ```ts return c.json({ ok: true }); // 200 JSON return c.json({ error: 'Bad request' }, 400); // 400 JSON return c.text('Plain text', 200); // 200 text/plain return c.html('

Hello

', 200); // 200 text/html // Note: the gateway strips Location/Refresh headers from HTTP responses, // so return JSON (e.g. `{ redirectTo: '/login' }`) and navigate on the client. ``` Always pass the status code as the second argument (`c.json(data, 400)`). See [API Responses & Status Codes](/platform/responses-and-status-codes) for all platform and gateway response structures. ## 4. Request headers, response headers, and cookies - **Request headers:** In plain `main.ts`, read `req.headers['content-type']` (keys are lowercased). In Hono, read `c.req.header('content-type')`. `cookie`, `authorization`, and `proxy-authorization` are stripped at the gateway before your code runs; always read the verified user from `ctx.user` (or `c.env.user`), never from headers. - **Response headers:** In plain `main.ts`, pass `{ headers: { ... } }` to `new Response(...)`. In Hono, stage headers with `c.header(name, value)`: ```ts app.get('/notes', async (c) => { c.header('cache-control', 'no-store'); c.header('x-request-id', c.env.requestId); return c.json({ notes: [] }); }); ``` - **Cookies (`ctx.cookies`):** `ctx.cookies` provides `get(name)`, `has(name)`, `set(name, value, opts)`, and `delete(name)` (`fenaura_*` names are blocked), though the HTTP gateway strips inbound `cookie` headers and outbound `set-cookie` headers on deployed responses. Use Fenaura Auth endpoints for session cookies, or return state in JSON responses. ## 5. Database (`ctx.db`, `ctx.sql`, `ctx.pg`) and transactions `ctx.db.query(sql, params)` runs parameterized SQL (`$1`, `$2`, ...) and returns an array of row objects: ```ts const rows = await ctx.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [ctx.user.userId], ); ``` Using `ctx.pg` and `ctx.sql` with Drizzle: ```ts const notes = ctx.pg.pgTable('notes', { id: ctx.pg.uuid('id').primaryKey(), title: ctx.pg.text('title').notNull(), owner: ctx.pg.uuid('owner').notNull(), }); const list = await ctx.db.select().from(notes); const count = await ctx.db.execute(ctx.sql`select count(*)::int as n from notes`); ``` For multi-step writes that must succeed or roll back together, use `ctx.db.transaction(async (tx) => { ... })`: ```ts const result = await ctx.db.transaction(async (tx) => { const [note] = await tx.query( 'insert into notes (title, owner) values ($1, $2) returning *', ['First note', ctx.user.userId], ); await tx.query( 'update profiles set note_count = note_count + 1 where id = $1', [ctx.user.userId], ); return note; }); ``` If anything throws inside the callback, Fenaura automatically runs `ROLLBACK` so partial writes never land. Explicit `BEGIN`, `COMMIT`, `ROLLBACK`, and `SAVEPOINT` statements are also supported on `ctx.db.query(...)`. See [Drizzle in the edge](/database/drizzle) for the full database guide. ## 6. Redis (`ctx.redis`) `ctx.redis` is a real, project-isolated Redis client. Each project and environment (`test` vs `production`) has its own Redis database: ```ts const hits = await ctx.redis.incr(`views:${id}`); await ctx.redis.expire(`views:${id}`, 3600); await ctx.redis.setex('cache:summary', 60, JSON.stringify({ ok: true })); const cached = await ctx.redis.get('cache:summary'); ``` ## 7. Realtime (`ctx.realtime`) Publish events directly from a Fleet to connected WebSocket clients, or issue scoped channel tokens: ```ts // Broadcast an event to all subscribers listening on 'room:general' await ctx.realtime.publish('room:general', 'message.created', { id: note.id, title: note.title, authorId: ctx.user.userId, }); // Mint a channel token for a private topic const tok = await ctx.realtime.token(`user:${ctx.user.userId}`, { ttlSeconds: 300 }); ``` ## 8. Storage (`ctx.storage`) and images (`ctx.image`) `ctx.storage.from(bucket)` mirrors the Supabase storage shape with per-user isolation. Edge uploads are capped at 4 MiB: ```ts const bucket = ctx.storage.from('avatars'); await bucket.upload('avatar.png', bytes, { contentType: 'image/png', upsert: true, }); const { data, size } = await bucket.download('avatar.png'); const files = await bucket.list({ prefix: '' }); const exists = await bucket.exists('avatar.png'); const signed = await bucket.getUrl('avatar.png'); const pub = await bucket.getPublicUrl('avatar.png'); const thumbUrl = await bucket.getTransformUrl('avatar.png', { width: 200, height: 200 }); await bucket.remove(['avatar.png']); ``` `ctx.storage.system.from(bucket)` acts as the project without per-user folder isolation. `ctx.storage.listBuckets()` and `ctx.storage.createBucket(name, opts)` manage buckets. For on-the-fly image transforms via `ctx.image`: ```ts const transformed = await ctx.image.transform('avatars', 'avatar.png', { width: 200, height: 200, }); const url = await ctx.image.getTransformUrl('avatars', 'avatar.png', { width: 200, }); ``` ## 9. Email (`ctx.email`) ```ts await ctx.email.send({ to: 'ada@example.com', subject: 'Welcome', html: '

Your account is ready.

', text: 'Your account is ready.', }); ``` In development (`ctx.environment === 'test'`), emails are captured in your Dev Mailbox instead of being delivered externally. ## 10. Outbound HTTP (`fetch`) Global `fetch(url, options)` is SSRF-protected by the Rust gateway (private IP ranges blocked, redirect targets re-validated). Responses provide `status`, `ok`, `headers`, `json()`, `text()`, `arrayBuffer()`, `bytes()`, and `body_base64` (for binary fidelity on images/PDFs): ```ts const res = await fetch('https://api.stripe.com/v1/customers', { method: 'POST', headers: { Authorization: `Bearer ${ctx.env.STRIPE_SECRET_KEY}`, 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'email=ada@example.com', }); const customer = await res.json(); ``` ## 11. Logging (`ctx.log`, `console`) and background work (`ctx.waitUntil`) Always use `ctx.log` for structured logs (`debug`, `info`, `warn`, `error`) and `ctx.log.child(bindings)` to attach shared fields to every entry. `ctx` is globally available in plain handlers, TypeScript/JavaScript modules, and Hono routes, so use `ctx.log` everywhere (never `ctx.env.log`, because `ctx.env` holds your environment variables only): ```ts ctx.log.info('Note created', { noteId: rows[0].id, userId: ctx.user.userId }); const reqLog = ctx.log.child({ route: '/notes', userId: ctx.user.userId }); reqLog.warn('Slow query', { ms: 420 }); ``` `console.log`, `console.warn`, and `console.error` are also captured (as `info`, `warn`, and `error`), though `ctx.log` is recommended for structured `data` objects and `debug` level. **Built-in safety caps & redaction:** - Up to `100` log entries per invocation; strings truncate at `2000` characters (`2048` for `console.*` args), objects serialize up to depth `6` with `100` keys/array items max and circular-reference protection. - Keys matching secret patterns (`password`, `secret`, `token`, `api_key`, `dev_key`, `private_key`, `authorization`, `cookie`, `session`, `credential`, `dsn`, `otp`, `signature`) are automatically replaced with `[redacted]`. `ctx.waitUntil(promise)` runs background work after the HTTP response is sent: ```ts ctx.waitUntil( ctx.email.send({ to: 'ada@example.com', subject: 'Saved', text: 'Done' }), ); return ctx.json({ ok: true }); ``` ## 12. Environment variables and npm packages - **Environment variables:** Read from `ctx.env.STRIPE_SECRET_KEY`, `c.env.STRIPE_SECRET_KEY` (Hono), `Deno.env.get('STRIPE_SECRET_KEY')`, or `process.env.STRIPE_SECRET_KEY`. Development and production variables are isolated; always check if a key is `undefined`. - **npm packages:** Import browser/edge-compatible npm packages (e.g. `import { z } from 'zod'`) from any file. Packages installed with `npm install ` in the Fleet IDE terminal, or by Veilo, live in the project's database-backed virtual `node_modules` and are resolved first. Uninstalled bare imports fall back to `esm.sh` at deploy time. `hono` is built in at zero bundle cost. See [Using npm packages](/fleets/ide#using-npm-packages). ## 13. What is not in the isolate Fleets run in a sandboxed V8 isolate, not Node.js. There is no `fs`, no `child_process`, no `require()`, no `eval()` / `new Function()`, and no `WebAssembly`. --- # Environments URL: https://docs.fenaura.dev/fleets/environments Section: Fleets # Environments Every project has two environments, and they behave differently on purpose. ## Same code, different deployment The Development/Production switch in the project header does not rewrite your source code. It points the dashboard and your Fleet deployments at a different set of resources: a different Postgres database, a different Redis database, separate storage buckets, separate Platform secrets and environment variables, and a separate set of end users. The Fleet editor, the files and the code are the same. You write once and deploy twice, once to the `dev-` URL and once to the production URL. Your laptop is just another place to run that same code against Development resources, it is not a separate kind of backend. Inside a running Fleet handler you can ask which environment it is: ```ts export default async (req: Request, ctx: any) => { const isDev = ctx.environment === 'test'; // In Development, skip the external call and use a harmless dummy value. // In Production, use the real integration. const apiKey = isDev ? 'dummy-key' : ctx.env.PAYMENT_API_KEY; if (!isDev && !apiKey) return ctx.json({ error: 'PAYMENT_API_KEY is missing' }, 500); return ctx.json({ env: ctx.environment, apiKey: isDev ? 'dummy' : 'live' }); }; ``` `ctx.environment` is `'test'` in Development and `'production'` in Production. It is injected by the runtime from the deployment target, so it is reliable on both the proxy path and the direct Fleet URL. `ctx.env` is also separate per environment: set the same key in both places with different values, and the handler picks up the value for the environment it is running in. ```render img:docs-dev-url-gate|The development URL is gated by your dev key or owner session, the production Fleet URL by an end-user session at the edge ``` The URL is the only visible difference. Everything behind it is separate. ## What is separate | | Development | Production | |---|---|---| | Database | its own | real user data | | Redis | development Redis database | production Redis database | | Storage | its own | real files | | Environment variables | its own values | its own values | | End users | test users | real users | | Email | trapped, not delivered | delivered | "Trapped" means an email sent in development does not reach a real inbox. It is captured so you can read it. This is not a setting you switch on, it is what the development environment is for. Because the separation is physical rather than a filter, a bug in development cannot write a row a customer will see. There is no query you can run from the development environment that reaches production data. ## One codebase You deploy the same source to both. There are no per-environment branches to maintain, and no `if (isProd)` scattered through your handlers. The platform resolves the environment at runtime, from the URL the request arrived on: - request hits `dev-{token}` › development database, Redis, storage, variables - request hits `{token}` › production database, Redis, storage, variables Your code asks for `ctx.env.STRIPE_SECRET_KEY` and gets whichever value belongs to the environment handling the request. ## Secret names are shared, values are not This is the part that saves the most pain. You add a variable once: ``` STRIPE_SECRET_KEY dev: sk_test_51H... prod: sk_live_51H... PUBLIC_BASE_URL dev: http://localhost prod: https://app.example.com ``` The name is the contract. Because both environments hold the same names, code that works in development cannot fail in production for a missing variable, the name is there, only the value differs. The reverse is the trap: a variable you add **only** in development is missing in production, and the first request that needs it fails. Add it in both. ## The private dev key A development URL is not public. It answers only when the caller proves they are allowed to use it: - a valid `X-Fenaura-Dev-Key` header, or - an active development session ```bash FLEET_URL="https://edge.fenaura.dev/dev-k7m9x2p" curl "$FLEET_URL/api/notes" \ -H "X-Fenaura-Dev-Key: $FENAURA_DEV_KEY" ``` Without either, the request is refused before your code runs: ``` 401 DEV_ACCESS_DENIED ``` Use `X-Fenaura-Dev-Key` strictly in CLI, `curl`, or server-side test scripts, never commit it or expose it in frontend `VITE_*` variables. In a browser app, signed-in and approved development users authenticate automatically via their session cookie (`credentials: 'include'`). ## A development URL goes away after deploy Development URLs are provisional, not permanent. They exist to let you try code before it is live, and they are not the address your application should ship. The rule to hold onto: - Your application calls the **production** URL. - Your tests and your own machine call the **development** URL, with the dev key. - Do not hard-code any URL into a client you distribute; read it from configuration. If a request arrives at a development URL without the key, it is refused. So a misconfigured release does not quietly write test data into someone's project, it fails, visibly, with `DEV_ACCESS_DENIED`. ## What a deploy does A deploy promotes code, not data: 1. The platform compiles the Fleet. A compile error stops the deploy. 2. The new version becomes active for that environment. 3. The previous version is kept in the version timeline. Nothing in the database moves. Deploying production code does not touch development data, and deploying to development does not touch production. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [The context object](/fleets/context): reading `ctx.env` and knowing the environment. - [The IDE](/fleets/ide): deploying from the editor. - [Rate limits](/edge/rate-limits): preview and production budgets. --- # The database URL: https://docs.fenaura.dev/fleets/database Section: Fleets # The database Every project has a Postgres database. It exists before you write any code, it is already connected, and it is already scoped. ## Nothing to connect There is no connection string, no pool to create, no credential to rotate. Inside a Fleet: ```ts const rows = await ctx.db.query('select * from notes where owner = $1::uuid', [ctx.user.userId]); const raw = await ctx.db.execute(ctx.sql`select count(*) from notes`); ``` Both work on the first request. The runtime owns the connection and reuses it across invocations, so a cold start does not open a new one for every call. ## Two ways to query **`ctx.db` Drizzle query builder (`select`, `insert`, `update`, `delete`).** Define your table with `ctx.pg` (`pgTable`, `uuid`, `text`, etc.) and query with Drizzle: ```ts import { eq, and, desc } from 'drizzle-orm'; const notes = ctx.pg.pgTable('notes', { id: ctx.pg.uuid('id').primaryKey(), title: ctx.pg.text('title'), owner: ctx.pg.uuid('owner'), status: ctx.pg.text('status'), created_at: ctx.pg.timestamp('created_at'), }); const rows = await ctx.db .select() .from(notes) .where(and(eq(notes.owner, ctx.user.userId), eq(notes.status, 'open'))) .orderBy(desc(notes.created_at)) .limit(20); ``` *(Note: `ctx.db.query(sql, params)` is Fenaura's raw parameterized SQL helper, not Drizzle's relational `db.query.` API.)* **`ctx.db.query(sql, params)` or `ctx.db.execute(ctx.sql\`...\`)`, raw SQL.** For aggregates, CTEs, and window functions: ```ts const stats = await ctx.db.query( `select owner, count(*) as total from notes group by owner order by total desc`, ); ``` When using `ctx.sql`, remember that ``ctx.sql`...` `` builds a Drizzle `SQL` object synchronously and must be passed to `ctx.db.execute(...)` to run: ```ts await ctx.db.execute(ctx.sql`select * from notes where title = ${term}`); // bound safely ``` The same data, the same connection. Use whichever reads better for the query in front of you. ## Development and production are separate databases A development Fleet writes to a development database. A production Fleet writes to the production one. This is physical separation, not a filter: - a row inserted in development does not appear in production - a query run in production cannot see development rows - a migration applied in one does not silently apply in the other A test that clears a table therefore clears the test table. That single fact removes most of the fear from writing a script that deletes things. ## Transactions `ctx.db.transaction(async (tx) => ...)` runs your callback inside `BEGIN` / `COMMIT` (and automatically `ROLLBACK`s if the callback throws or calls `tx.rollback()`). Inside the callback, `tx` exposes `tx.query`, `tx.execute`, `tx.select`, `tx.insert`, `tx.update`, `tx.delete`, and `tx.rollback`: ```ts await ctx.db.transaction(async (tx) => { await tx.query('insert into ledger (account, amount) values ($1, $2)', [from, -100]); await tx.query('insert into ledger (account, amount) values ($1, $2)', [to, 100]); }); ``` **A unique key for idempotency.** A retried request cannot charge twice: ```ts await ctx.db.insert(payments) .values({ idempotency_key: key, amount }) .onConflictDoNothing(); ``` **Intent first, then effect.** Write the intent row, do the work, mark it done. A crash leaves a row you can finish later, which an in-memory transaction cannot protect you from anyway. Never send email or call a third party inside a transaction you do have; an external side effect cannot be rolled back. ## Schema Tables are defined once and migrated forward. The migration surface is covered in [Database › Migrations](/database/migrations), and the Drizzle language itself at [orm.drizzle.team](https://orm.drizzle.team). Two things worth knowing early: **Add, do not rename.** Adding a nullable column is safe and instant. Renaming one breaks every deploy still running the old code. Add the new column, write to both, then drop the old one in a later deploy. **Give every table an owner.** A `user_id` (or `owner`) column makes row-level security possible and makes "who can see this?" answerable. Adding it later means backfilling rows you can no longer attribute. ## The users table already exists Every project database is provisioned with a `public.users` table. You do not create it, and you should not drop it. It is created on first provision and re-created idempotently for older projects, so it is there the first time you query: ```sql id uuid primary key default gen_random_uuid() email citext unique name text avatar_url text metadata jsonb default '{}'::jsonb status text default 'active' created_at timestamptz default now() updated_at timestamptz default now() ``` It is a registry table with grants for your app, ready for looking users up, segmenting an audience, and targeting a batch send. It is not your auth table (Fenaura's auth lives in its own store), so treat it as a place to keep your app's view of a user rather than as the source of truth for sessions. It is also protected: dropping it, or dropping or renaming its `id` or `email` columns, is refused with `PROTECTED_USERS_COLUMN_LOCKED` in both environments. ### Adding a role column A `role` column is the usual next step, and the default is what makes it safe to introduce on a live table: ```sql ALTER TABLE users ADD COLUMN role text NOT NULL DEFAULT 'user'; ``` The `DEFAULT 'user'` means every existing row gets a value in the same statement, so no row is ever in a state where the role is undefined. Without a default you would have to add the column nullable, backfill, then add the constraint: three deploys instead of one, with a window where some code sees `NULL`. Then read it explicitly rather than by truthiness: ```ts const [user] = await ctx.db.query('select id, role from users where id = $1::uuid limit 1', [id]); if (user?.role !== 'admin') return ctx.json({ error: 'forbidden' }, 403); ``` Be careful with the comparison. `if (user.role)` and `if (!user.role)` will surprise you the moment someone stores `'false'`, `'0'` or an empty string. Check against the exact value you mean. ## Row-level security Policies let the database enforce ownership, so a bug in one handler cannot leak another user's rows. See [What Row Level Security protects](/database/rls) for the model and [Security](/database/security) for how to write a policy. The short version: a policy filters rows to the current user, so a query that forgets a `where` clause still cannot return someone else's row *when it runs as an RLS-subject role*. **Be precise about which role you are.** Fleets connect to your project database as the project's **owner** role, so Drizzle inside a Fleet is full-power: RLS is enabled on your tables, but the owner is not subject to its own policies. That is deliberate, otherwise your own service code could not read the rows it just wrote. The consequence is the one to remember: > Inside a Fleet, **you** are the access control. `ctx.db` will happily return every row in the table. Scope every query by the user you resolved from the session, and never pass a request-supplied `user_id` through as if it were trusted. > > Do not rely on a policy to save a Fleet query that forgot its `where`. The RLS-subject role (`api_`, a non-owner that *is* bound by policies) is what serves the data API path. That is where a policy does the work for you, and it is why "can user A read user B's data through the data API" has a safe answer while the same question about a Fleet handler depends on your own code. The database-level invariant still holds either way: an event trigger enables RLS on every `CREATE TABLE`, and a disable attempt is undone inside the same transaction. So RLS is always on. The only open question is who is subject to it. ## Redis next to it For anything short-lived, a counter, a cache, a rate limit of your own, there is `ctx.redis`, already connected to this project's Redis database. Details in [the context object](/fleets/context#ctx-redis). ## Next - [The IDE](/fleets/ide): deploying from the editor. - [Storage](/storage): files, next to the rows. - [Veilo](/veilo): the agent that writes this with you. --- # The IDE URL: https://docs.fenaura.dev/fleets/ide Section: Fleets # The IDE Fleets are edited in a browser IDE, not a text box. Everything below is in the same place, and each part exists because writing server code needs it. ## Files and folders The file tree shows real directories. Create folders, move files, and import between them: ```ts import { listNotes } from './controllers/notes'; import { validate } from '../lib/validate'; ``` Imports resolve the way they do in a bundler, and a compile check runs before a deploy. A file that cannot resolve is an error you see, not a deploy that fails in production. ## The terminal The bottom panel has a terminal that runs **IDE commands**, not a shell. Type `help` for the list: | Command | What it does | |---|---| | `help` | list every command | | `build` | compile the Fleet and report errors | | `deploy` | ship the current code | | `save` | save the current file | | `fmt` | format the code | | `open ` | open a file by name | | `files` | list the project files | | `ctx` | show what the runtime provides | | `env ` | switch the environment view | | `versions` | list past deploys | | `clear` | clear the terminal | It is a command interpreter, and that is the point: the things you do most often while writing code take one word and no mouse. ## Deploying `deploy` from the terminal, or the deploy button. Before it ships: 1. The code is bundled, an error here stops the deploy and points at the line. 2. The new version becomes active for the chosen environment. 3. The previous version stays in the version timeline. Deploying to `test` does not touch production and vice versa. Same code, chosen environment, separate data. ## Versions Every deploy is kept. The timeline lets you see what changed and when, and go back if a change was wrong. This is the safety net that makes deploying without fear reasonable, you are not overwriting the only copy. ## Source control Single-branch model (`main`): stage, unstage, commit to `main`, view commit diffs, and browse **Changes**, **Commits**, **Releases**, and **Policy**. If you have not used Git before, the useful habit is: commit when something works, so you can return to it. ## The problems panel and Recycle Bin The problems panel lists compile and type errors and jumps to the line. Deleted files go to the **Recycle Bin** (accessible from the IDE or **File Recovery & Trash** in Settings), so a delete is recoverable rather than final. ## Where to start - Edit a file in the tree. - `build` to check it compiles. - `deploy` to the test environment. - Call the development URL with your dev key to see it work. Nothing here needs a local toolchain, Node version, or build machine on your device, the IDE is the environment. ## Using npm packages You can use packages from npm in two ways: 1. **Import directly**, and the bundler resolves the package from `esm.sh` at deploy time (or pin a version with `npm:zod@3.23.8`). 2. **Install in the IDE terminal** with `npm install ` (plus `npm uninstall `, `npm ls`, and `npx `), which stores the package in the Fleet's virtual `node_modules` so the bundler resolves it first before falling back to `esm.sh`: ```ts import { z } from 'zod'; const Body = z.object({ title: z.string() }); ``` Pin a version with the `npm:` prefix when you want to lock one down: ```ts import { z } from 'npm:zod@3.23.8'; ``` How it works, and why it is safe: - The build resolves installed virtual `node_modules` first and falls back to `esm.sh` for unbundled imports, reporting a build error if an import cannot be resolved, the same way it does for a typo in a project file. - Nothing is installed on your machine. Your deployed function runs in an isolated V8 isolate with bundled code only, so a package cannot reach your project from outside the sandbox. - Unpinned `esm.sh` imports re-resolve at deploy time, so pin a version or install via `npm install ` in the IDE terminal when version stability matters. - `hono` ships with the runtime: importing it works and adds nothing to your bundle, since the build maps it to the runtime's global Hono. ## Next - [Environments](/fleets/environments): dev and prod in detail. - [Veilo](/veilo): the agent that edits alongside you. - [Testing](/fleets/testing): calling your Fleets safely. --- # Testing URL: https://docs.fenaura.dev/fleets/testing Section: Fleets # Testing You can call a Fleet directly from your machine while building it. No tunnel, no local server, no mock. ## The private dev key The development URL answers only when the caller proves they belong to the project. Two ways, and the first is the usual one: ```bash # Copied from Project Overview -> Fleet URL (Full Fleet URL in Development) FLEET_URL="https://edge.fenaura.dev/dev-k7m9x2p" curl "$FLEET_URL/api/notes" \ -H "X-Fenaura-Dev-Key: $FENAURA_DEV_KEY" ``` Or, in the dashboard, an active development session counts without the header. A request with neither is refused before your code runs: ``` 401 DEV_ACCESS_DENIED ``` The key is what makes it safe to keep a development URL in a `.env` file or a test script. Knowing the URL is not enough. ## From your own code ```ts // Copied from Project Overview -> Fleet URL (Full Fleet URL in Development) & Dev private key const FLEET_URL = 'https://edge.fenaura.dev/dev-k7m9x2p'; const DEV_KEY = 'fndev_your_dev_private_key'; const res = await fetch(`${FLEET_URL}/api/notes`, { headers: { 'X-Fenaura-Dev-Key': DEV_KEY }, }); const { notes } = await res.json(); ``` For anything past a smoke test, get a real **end-user session** and send it as a bearer token, so your request is authenticated the way a browser's would be. That is what exercises your route as a user will experience it. ## No separate tool to reach for Most stacks need a testing tool bolted on: Postman for requests, a script for seeding, a dashboard you keep in another tab. The complexity is not the request, it is keeping five things in sync. Fenaura puts the pieces in the same place: **Kora** is the request workspace. It has your routes, an environment per any number of targets, the auth token, and a response viewer, and it saves and replays requests. It also imports **cURL** and **Postman v2** collections, so work you have already done comes with you rather than being retyped. And it syncs to a cloud workspace, so a request you built on one machine is there on another. **Veilo** is the agent. It can do the testing work directly: run a request, read the response, and tell you what failed. Because it can read your database, it can also check the other half of the story, that the row the request should have created actually exists. The practical upshot: the complexity of "set up a testing tool, then keep it current with the API" mostly does not arise. The requests live where the code does, and the agent can inspect both. ## Asking Veilo to check your work Things you can ask, in plain language: - "Call `/api/notes` and show me what it returns." - "Show me the last five rows in `notes`, and who created them." - "Join `orders` with `users` and show me the ten most recent with the user's email." - "Send a test email to me and confirm it landed in the dev mailbox." - "Get the related records for this user, their orders and their notes." That last one is worth noticing. Because Veilo reads the schema, it can follow relations without you writing the join. It is the same work you would do to answer "is this behaving correctly?", asked in one sentence. Anything that would touch **production** or delete data needs your approval first, see [Approvals](/veilo/approvals). ## Email in development An email sent from a development Fleet is **trapped**, not delivered. It lands in the dev mailbox, where you can read it, and no real inbox receives it. This is automatic, it is what the development environment is for. So you can test a signup flow end to end, including the verification email, without a single real address and without a chance of mailing a customer. ## A testing habit that holds Three checks catch most problems: 1. **Call it as a signed-out user.** A private route should return `401`, not data. 2. **Call it as the wrong user.** They should not see another user's rows. 3. **Call it twice.** The second call should not create a duplicate. Each of these is one request in Kora, and Veilo can run them for you. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Environments](/fleets/environments): what changes in production. - [Rate limits](/edge/rate-limits): the budgets your tests consume. - [Kora](/kora): the request workspace in detail. --- # Authentication overview URL: https://docs.fenaura.dev/auth Section: Authentication # Authentication overview End users are yours. They are rows in your project's database, not accounts on Fenaura. You can list them, revoke a session, block one, and delete one. ## The three parts **The SDK** runs in the browser and talks to the auth endpoints: signing up, signing in, resending a code, resetting a password. **The proxy** is a small set of files the installer writes into your frontend. They forward `/fenaura/*` requests to Fenaura so the session cookie is set by your own domain, where your app can use it. The cookie is HttpOnly, so nothing in your bundle can read or steal it. **The platform** stores the session and checks it on every edge request. An authentication check you could forget to write does not exist, because you do not write it. ## Install the proxy ```bash npx fenaura-auth-init ``` Run it once in your frontend folder. It detects your host and writes the forwarding rules for it: `public/_redirects` for Netlify and Cloudflare Pages, a rewrite in `vercel.json` for Vercel, your dev-server proxy for Vite, Next.js, SvelteKit, Astro and Nuxt, or the Live Server proxy for plain HTML projects. The full file list and what you will see printed is in [Installation](/sdk). ## Sign up and sign in ```ts import { createClient } from 'fenaura-sdk'; export const fenaura = createClient('/fenaura', 'your-project-id'); const { data, error } = await fenaura.auth.signUp({ email: 'ada@example.com', password: 'a-long-enough-password', }); ``` The first argument is the proxy path, the second is your Project ID. There is no secret in creating a client: the Project ID identifies your project and grants nothing by itself. See [createClient](/sdk/create-client). Passwords must be at least eight characters. Every auth method returns `{ data, error }` and never throws. ```ts const { data, error } = await fenaura.auth.signIn({ email: 'ada@example.com', password: 'a-long-enough-password', }); ``` On success, `data.session_minted` is true and the session cookie is set. Your code stores nothing. ## Check who is signed in ```ts const { data } = await fenaura.auth.getUser(); ``` `getUser()` asks the server and works with the session cookie, so it is the check to use. There is also `getSession()`, but in proxy mode it returns the in-memory token only, which normal web apps never set; the cookie that carries your session is HttpOnly and invisible to JavaScript by design. ## Sign out ```ts await fenaura.auth.signOut(); ``` This clears the session on the client and revokes it on the server. A revoked session stops working on the next edge request. ## Next - [Methods](/auth/methods): every call, every option. - [OAuth providers](/auth/oauth): the twelve, and callback setup. - [Sessions and cookies](/auth/sessions): what is set and how it is sent. --- # Methods URL: https://docs.fenaura.dev/auth/methods Section: Authentication # Methods Every auth method returns `{ data, error }`. Nothing throws, so check `error` rather than wrapping calls in `try`. The error half is always the same shape, whatever the status code: ```json { "data": null, "error": { "message": "Invalid or expired verification code.", "code": "INVALID_CODE", "status": 400 } } ``` A 4xx response is not a crash. It is a normal object your code can read and act on, the same way it reads success responses. `error.code` is stable machine text you can switch on; `error.message` is for showing. ## Sign up ```ts const { data, error } = await fenaura.auth.signUp({ email: 'ada@example.com', password: 'a-long-enough-password', }); if (error) throw error; ``` Without `fenaura-sdk` in a **browser** (exact `fetch` equivalent via your `/fenaura/*` proxy: sets the first-party `HttpOnly` cookie, saves the response, and handles `error` and `message` the same way): ```ts const res = await fetch('/fenaura/auth/dp/signup', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'ada@example.com', password: 'a-long-enough-password', project_id: 'your-project-uuid', }), }); const { data, error, message } = await res.json(); if (!res.ok || error) { throw new Error(error?.message || message || 'Sign up failed'); } ``` From a **mobile app, CLI, or your own backend server** (`browser_flow: false`: since it is not a browser, Fenaura hands you `data.token` directly so you send it subsequently in `Authorization: Bearer ` headers): ```ts const res = await fetch('https://api.fenaura.dev/auth/dp/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'ada@example.com', password: 'a-long-enough-password', project_id: 'your-project-uuid', browser_flow: false, }), }); const { data, error, message } = await res.json(); if (!res.ok || error) { throw new Error(error?.message || message || 'Sign up failed'); } const token = data.token; // Pass `Authorization: Bearer ${token}` on subsequent requests ``` Two fields: `email` and `password`. The password must be at least 8 characters. What happens next depends on one switch in your project settings. ```render img:docs-signup-verification-flow|Sign-up creates the account, a verification email may be required, the code is submitted, and the first session is minted as a cookie in browsers or a token outside them ``` ### The default: signed up means signed in Out of the box, signing up creates the user and starts the session in one step. In a browser the response carries no token at all: ```json { "status": "success", "data": { "session_minted": true, "pending_approval": false } } ``` `session_minted: true` is the whole story: Fenaura set the session cookie in the browser at the same moment. Your code stores nothing, refreshes nothing, and never touches a token. The user is on the next screen and every later request is signed in. ### Where the token actually is The session lives in a first-party cookie, not in the body. It is set with `HttpOnly`, `Secure` and `SameSite=Lax`, so JavaScript cannot read it and an XSS bug cannot steal it. That is on purpose: a token in the response body is a thing your front-end has to store, and every place you store it is a place it can leak from. Because the cookie is first party and set by Fenaura directly, the browser attaches it to every later request with no code from you. The cookie is named `fenaura_eusid` in production and `fenaura_eusid_dev` in development, so the two environments never overwrite each other while you test. One more field worth knowing: `pending_approval: true` means the account was created but the session cannot read or write data yet. That happens when owner approval is required for development users (on by default), or when email verification is required. The user exists; their session just cannot reach your data until the condition clears. ### The switch: require email verification If you want accounts confirmed by email first, there is one switch for it. Open your project's auth settings, General tab: [Set email verification as required](https://fenaura.dev/app/projects/your-project-id/auth?tab=general) That link is a real deep link: it opens the General tab of the auth settings for the project you have open. If you are not signed in yet, open your project in the dashboard and go to Auth settings and then General. **Turn this on before you build the code screen.** If the switch is left off, signup mints a session immediately, Fenaura sends no 6-digit code, `verification_required` never appears in the response, and `/auth/dp/verify-email` is never called. The flow below only happens when this switch is ON and saved. The switch is a plain checkbox with a plain label, exactly as it renders in the dashboard: ```render ``` Tick it and save. From then on, every newly created account in production is created unverified, and sign-ups change shape: ```json { "status": "success", "data": { "verification_required": true, "email": "ada@example.com", "message": "A verification code was sent to ada@example.com. The code expires in 10 minutes.", "expires_in": 600, "expires_in_display": "10 minutes" } } ``` The account is created, **no session starts**, and Fenaura sends the verification email for you. You did not configure an email provider, a template, or a send call. On most platforms this step is where the real work starts: picking a transactional email vendor, verifying a sending domain, writing HTML templates, wiring a send call into your signup route. Here the send is built in, the default template has the code in it, and the only thing you did was tick a checkbox. If you want your own wording, that is one page over in [Email templates](/email/templates). Sending is included too: every project has a monthly email allowance, 300 a month by default, and the email section explains the details. Show a code input when `verification_required` comes back, and submit the code the user received. In React: ```tsx react import { useState } from 'react'; const [code, setCode] = useState(''); setCode(e.target.value)} /> const { data, error } = await fenaura.auth.submitVerificationCode({ email: 'ada@example.com', code, }); if (error) throw error; // The first session starts here: session_minted: true ``` ```tsx solid const [code, setCode] = createSignal(''); setCode(e.currentTarget.value)} /> const { data, error } = await fenaura.auth.submitVerificationCode({ email: 'ada@example.com', code: code(), }); if (error) throw error; // The first session starts here: session_minted: true ``` ```html vue const { data, error } = await fenaura.auth.submitVerificationCode({ email: 'ada@example.com', code, }); if (error) throw error; // The first session starts here: session_minted: true ``` ```html angular const { data, error } = await fenaura.auth.submitVerificationCode({ email: 'ada@example.com', code, }); if (error) throw error; // The first session starts here: session_minted: true ``` That is the whole integration: one call to sign up, one call to confirm. The first session is minted when the code is accepted, and the cookie appears then: a `fenaura_eusid_...` cookie on your own domain, HttpOnly and opaque, not a JWT. Your code never reads it; the browser carries it and every later request is signed in. You can see it in devtools under Application and Cookies. What is inside it and how it travels: [Sessions and cookies](/auth/sessions). Details worth knowing: - The code expires after 10 minutes; the response says so in both `expires_in` (seconds, for programs) and `expires_in_display` ("10 minutes", for showing people). - A wrong code returns an error; after 5 wrong attempts in 10 minutes the address is throttled for a while. - The user can ask for a fresh code with `sendVerificationCode`. - This gate applies to every newly created account in production. Development sign-ups never wait on a code, so testing stays fast. To sign up development users from the SDK, create the client with `{ env: 'development' }`: [Environments](/environments). ### Unverified users who try to sign up or sign in again If a user signs up, closes the tab before entering their verification code, and later tries to **sign up again** or **sign in** with the same email, Fenaura detects the unverified account automatically so your app can route them straight back to the verification screen and offer a **Resend** button: 1. **Signing up again while unverified:** Fenaura keeps the existing unexpired code valid (instead of burning extra resend quota) and returns: ```json { "status": "success", "data": { "verification_required": true, "code_already_sent": true, "already_pending": true, "email": "ada@example.com", "message": "A verification code was already sent to ada@example.com. Enter it below, or tap Resend if you didn't receive it." } } ``` 2. **Signing in while unverified:** Fenaura returns HTTP `401` with `error.code === 'EMAIL_NOT_VERIFIED'` so your sign-in form can catch it and redirect to verification: ```ts const { data, error } = await fenaura.auth.signIn({ email, password }); if (error?.code === 'EMAIL_NOT_VERIFIED') { // Route the user to your verification code screen router.push(`/verify?email=${encodeURIComponent(email)}`); return; } ``` 3. **Offering a Resend button on your verification page:** ```ts const { error } = await fenaura.auth.sendVerificationCode({ email }); if (error) showToast(error.message); else showToast('A new verification code was sent to your email.'); ``` Note: **Welcome emails are off by default.** If you want Fenaura to send a welcome message automatically after a user verifies their account, enable **Welcome email** in Auth Settings or Mailmy. - If a user signs up twice before confirming, the second sign-up re-sends the code instead of failing. An already-verified email signing up again returns `ACCOUNT_EXISTS`; tell the user to sign in. ### The other switch: require approval for development users Development is open by default, which is right for most projects. If your development environment holds data you would not show strangers, there is a second switch next to the first one, in the same General tab: ```render ``` With it on, development sign-ups still create the account and still show up in your Users tab, but the session cannot make data requests until you approve the user. Sign-up and sign-in responses carry `pending_approval: true`, and `getUser()` reports it too: ```ts const { data, error } = await fenaura.auth.getUser(); // data.user.pendingApproval === true while the account waits for approval ``` Your app can read that flag and show a "waiting for approval" screen. In the dashboard, the user's row shows **Awaiting approval** and the row menu gains an **Approve** action. Approval is not a one-time gate on the account creation; it is a state the user stays in until you change it. Approved users sign in normally from then on, on every device, with no re-approval. Unapproving works the same way in reverse and takes effect on the very next request: the same session that made successful reads a second ago gets rejected until you approve again. You do not need to delete or block the user to cut off a development session. Two rails come with the switch so it cannot be flooded: development sign-up rate limiting tightens, and the pending queue caps at 100 accounts. When the cap is reached, new sign-ups stop until you clear the queue. ### Resend the code ```ts await fenaura.auth.sendVerificationCode({ email: 'ada@example.com' }); ``` The response tells the user when their new code stops working: ```json { "status": "success", "data": { "code_sent": true, "email": "ada@example.com", "expires_in": 600, "expires_in_display": "10 minutes" } } ``` Signup already sent one; call this when the user asks, not on a timer. Resends are rate limited per project and per email address: 5 codes per address per hour, and 10 send attempts per IP per minute. Exceeding them returns `RATE_LIMITED` with a hint to wait an hour, so a stuck user is better off checking spam than hammering the button. ## Sign in ```ts const { data, error } = await fenaura.auth.signIn({ email: 'ada@example.com', password: 'a-long-enough-password', }); // data is { session_minted: true } ``` Same shape as the default sign-up: the session starts, the cookie is set, your code stores nothing. For a project with verification required, signing in with an unverified email returns an error, and Fenaura emails a fresh code at the same moment. Submit it with `submitVerificationCode` exactly as in the sign-up flow above, and the session starts. ## Sign out ```ts await fenaura.auth.signOut(); ``` Revokes the session on the server and clears the cookie. The next request is unsigned. ## Who is signed in ```ts const { data, error } = await fenaura.auth.getUser(); // data.user is the signed-in end user: // { endUserId, projectId, email, scopedIdentifier, identifierType, ... } ``` `getUser()` hits the server, so it reflects a session that was revoked in another tab. Use it when correctness matters, such as before a destructive action. ## Password reset Two steps, in this order: ```ts // 1. Request the code. Fenaura emails it. await fenaura.auth.sendPasswordReset({ email: 'ada@example.com' }); // 2. Submit the code with the new password. const { data, error } = await fenaura.auth.confirmPasswordReset({ email: 'ada@example.com', code: '123456', newPassword: 'a-new-long-password', }); ``` You cannot set a new password without the code. Requesting a reset for an address that has no account returns a generic success, so nobody can probe which emails signed up. ## Magic link ```ts await fenaura.auth.sendMagicLink({ email: 'ada@example.com' }); // later, when the user types the code from the email: const { data, error } = await fenaura.auth.verifyMagicCode({ email: 'ada@example.com', code: '123456', }); ``` ## OAuth ```ts await fenaura.auth.signInWithOAuth('github'); ``` This navigates the browser to the provider. When it returns, the platform exchanges the one-time code for a session. See [OAuth providers](/auth/oauth) for setup and the full list. ## Reacting to auth changes ```ts const unsubscribe = fenaura.auth.onAuthStateChange((event, session) => { // event: 'SIGNED_IN' | 'SIGNED_OUT' console.log(event); }); // later unsubscribe(); ``` Use this instead of polling. It fires when a sign-in, sign-up or sign-out succeeds in the current tab. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct `https://api.fenaura.dev` and `https://edge.fenaura.dev` URL on one page. - [API Responses & Status Codes](/platform/responses-and-status-codes#signup-verification-required-response): full property breakdown of `verification_required` and every auth response. - [Pure fetch & mobile API](/sdk/fetch): full plain-HTTP guide (signup, login, verification, reset, OAuth, storage, queries). - [Backend auth implementation](/backend-auth-implementation): full server code for proxying auth with `browser_flow: false`. - [Sessions and cookies](/auth/sessions): the cookie Fenaura set, and what it is. - [OAuth providers](/auth/oauth): provider list, callbacks, and mobile deep links. - [End-user management](/auth/end-users): revoke, block, delete, and Supabase bcrypt bulk import. --- # OAuth providers URL: https://docs.fenaura.dev/auth/oauth Section: Authentication # OAuth providers Fenaura supports twelve providers. All of them use the same call, so switching provider is one string. | Provider | Identifier | |---|---| | Apple | `apple` | | Discord | `discord` | | Facebook | `facebook` | | GitHub | `github` | | GitLab | `gitlab` | | Google | `google` | | LinkedIn | `linkedin` | | Microsoft | `microsoft` | | Slack | `slack` | | Spotify | `spotify` | | Twitch | `twitch` | | Twitter | `twitter` | ## Starting the flow ```ts await fenaura.auth.signInWithOAuth({ provider: 'github', redirectTo: `${window.location.origin}/auth/callback`, }); ``` This sends the browser to the provider. The user approves, the provider sends them back to Fenaura, and Fenaura sends them to your `redirectTo` with a one-time code in the URL. ```render img:docs-oauth-redirect-flow|Your app sends the browser to Fenaura, Fenaura redirects to the provider, the provider returns a one-time code, and the callback sets an HttpOnly session cookie ``` ## Finishing the flow On your callback page, exchange the code for a session: ```ts const params = new URLSearchParams(window.location.search); const code = params.get('code'); if (code) { const { data, error } = await fenaura.auth.exchangeOAuthCode({ code }); if (error) { // show a retry, do not sign the user in } } ``` Codes are single-use and expire after sixty seconds. A code that arrives twice, or arrives late, fails, that is why the exchange must happen on the callback page and not somewhere further into the app. ## Without the SDK (plain HTTP `fetch`) Open the provider authorization URL directly (`project_id` is your **Project UUID**, and `redirect_to` must belong to your registered **Allowed Origins** in Auth Settings): ```text https://api.fenaura.dev/oauth/google?project_id=&redirect_to= ``` When Fenaura redirects back with `?code=<64-hex-code>`, redeem it immediately with plain `fetch`: ```ts // From a web browser using /fenaura proxy (also sets HttpOnly cookie) const res = await fetch('/fenaura/auth/oauth/exchange', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ code }), }); // From your custom backend server or mobile app (direct URL -> returns data.token) const direct = await fetch('https://api.fenaura.dev/auth/oauth/exchange', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); const { data } = await direct.json(); // data = { token: "...", project_id: "...", session_minted: true } ``` ## Mobile apps (Kotlin, Flutter, deep links) Mobile apps (Android, iOS, Flutter, Kotlin Multiplatform, React Native) all share the exact same HTTP OAuth flow: 1. In your project's **Auth Settings › Allowed Origins**, add your custom app deep-link scheme (for example, `myapp://callback`) alongside any web origins. 2. In your **Auth Settings › Providers**, configure the provider credentials and set the default redirect URL (or pass `redirect_to=myapp://callback` per request). 3. Launch the system browser (Chrome Custom Tabs on Android / `ASWebAuthenticationSession` on iOS / `url_launcher` in Flutter) at: `https://api.fenaura.dev/oauth/?project_id=&redirect_to=myapp%3A%2F%2Fcallback` 4. Your app catches the `myapp://callback?code=...` intent/link and calls `POST https://api.fenaura.dev/auth/oauth/exchange` with `{"code": "..."}`. 5. Store the returned `data.token` securely and send `Authorization: Bearer ` on `/data`, `/blob`, and `/auth/dp/whoami`. > [!NOTE] > OAuth provider identities currently sign users into **Production**. Make sure every provider's client ID, secret, and allowed deep link origin are saved under Production Auth Settings. ### Kotlin / Android (plain HTTP) ```kotlin import java.net.URI import java.net.URLEncoder import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.charset.StandardCharsets // 1. Open this URL in Chrome Custom Tabs / system browser (works for google, github, apple, etc.) fun buildOAuthStartUrl(provider: String, projectUuid: String, deepLink: String = "myapp://callback"): String { val encRedirect = URLEncoder.encode(deepLink, StandardCharsets.UTF_8) val encProject = URLEncoder.encode(projectUuid, StandardCharsets.UTF_8) return "https://api.fenaura.dev/oauth/$provider?project_id=$encProject&redirect_to=$encRedirect" } // 2. When Android Intent receives myapp://callback?code=..., exchange the code for data.token fun exchangeOAuthCode(code: String): String { val client = HttpClient.newHttpClient() val req = HttpRequest.newBuilder() .uri(URI.create("https://api.fenaura.dev/auth/oauth/exchange")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("""{"code":"$code"}""")) .build() val res = client.send(req, HttpResponse.BodyHandlers.ofString()) return res.body() // parse JSON: data.token -> EncryptedSharedPreferences / Keystore } ``` ### Flutter / Dart (plain HTTP) ```dart import 'dart:convert'; import 'package:http/http.dart' as http; // 1. Open with url_launcher (LaunchMode.externalApplication): Uri buildOAuthStartUri(String provider, String projectUuid, {String redirectTo = 'myapp://callback'}) { return Uri.https('api.fenaura.dev', '/oauth/$provider', { 'project_id': projectUuid, 'redirect_to': redirectTo, }); } // 2. In your app_links listener for myapp://callback?code=..., exchange the code: Future exchangeOAuthCode(String code) async { final res = await http.post( Uri.parse('https://api.fenaura.dev/auth/oauth/exchange'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'code': code}), ); final body = jsonDecode(res.body) as Map; if (res.statusCode >= 400 || body['status'] == 'error') { throw Exception(body['message'] ?? 'OAuth exchange failed'); } return body['data']['token'] as String; // save to flutter_secure_storage } ``` ## Setting up a provider Each provider needs a callback URL registered on its side. The value is the same shape for all of them: ``` https://api.fenaura.dev/oauth/{provider}/callback ``` Replace `{provider}` with the identifier from the table. Both the development and production environments need their own registration if you use OAuth in both. You supply the client id and client secret in the project's auth settings. ### What differs per provider The call is the same for all twelve; the setup on the provider's side is not. These are the differences that actually bite, with the console where you create the app and copy the id and secret: | Provider | Setup notes | Create the app at | |---|---|---| | Google | Uses PKCE (S256). Enable the People and email scopes. | [Google Cloud - Credentials](https://console.cloud.google.com/apis/credentials) | | GitHub | The straightforward one: register the callback, copy id and secret. | [GitHub - OAuth Apps](https://github.com/settings/developers) | | Microsoft | Uses PKCE (S256). Extra field in the form: the tenant type (Entra ID organization, personal accounts, or both). | [Entra admin center - App registrations](https://entra.microsoft.com/) | | Apple | The only provider without a plain client secret: you generate the secret yourself as an ES256-signed JWT from a service key, and it expires, so you renew it. Needs a Services ID plus a Key. | [Apple Developer - Services IDs + Keys](https://developer.apple.com/account/resources/identifiers/list/serviceId) | | Facebook | Standard Facebook Login app setup. | [Meta for Developers - Apps](https://developers.facebook.com/apps/) | | X / Twitter | OAuth 2.0 with PKCE. If the provider withholds the email, Fenaura falls back to the username as the identifier. | [X Developer Portal - Project App](https://developer.x.com/en/portal/dashboard) | | Discord | Standard OAuth2 application. | [Discord - OAuth2](https://discord.com/developers/applications) | | LinkedIn | Uses OpenID Connect with PKCE (S256). | [LinkedIn - App - Auth](https://www.linkedin.com/developers/apps) | | Spotify | Uses PKCE (S256). | [Spotify Developer Dashboard](https://developer.spotify.com/dashboard) | | Slack | Uses OpenID Connect with PKCE (S256); pick the OpenID Connect token type in the app settings. | [api.slack.com - Your Apps](https://api.slack.com/apps) | | GitLab | Add the `read_user` scope when you create the application. | [GitLab - User Settings - Applications](https://gitlab.com/-/user_settings/applications) | | Twitch | Requests the `user:read:email` scope. | [Twitch Developer Console](https://dev.twitch.tv/console/apps) | For Google, enable the "People" and "email" scopes; for Apple, generate the client secret from a service key. ## What you get back The end user is created on first sign-in if they do not exist. `data.user` contains the provider's id, the email if the provider released it, and the display name where the provider sent one. Some providers do not release an email address. Do not assume `user.email` is set for OAuth users; key your own records on `user.endUserId`. ## Errors worth handling | Symptom | Cause | |---|---| | `provider_not_configured` | No client id/secret in the project's auth settings | | A redirect back with no `code` | The user cancelled, or the callback URL is not registered | | Exchange fails immediately | The code is older than sixty seconds or was already used | | Works in development, fails in production | The provider has a callback registered for only one environment | ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Methods](/auth/methods): the rest of the auth surface. - [Sessions and cookies](/auth/sessions): what happens after the exchange. --- # Sessions and cookies URL: https://docs.fenaura.dev/auth/sessions Section: Authentication # Sessions and cookies A session is what makes a request "signed in". The platform issues it, the browser or app carries it, and the edge runtime checks it before your function runs. ## The three ways to carry a session In priority order: 1. `Authorization: Bearer ` 2. `X-Fenaura-EUSID: ` 3. A session cookie The header wins over the cookie. That matters for two real cases: a native app or a command-line script has no cookie jar, so it holds the token itself; and a browser extension can send the header without touching the page's cookies. ```bash # Copied from Project Overview -> Fleet URL (Full Fleet URL) FLEET_URL="https://edge.fenaura.dev/k7m9x2p" # Call a Fleet route with an end-user session token (populates ctx.user) curl "$FLEET_URL/api/notes" \ -H "Authorization: Bearer " ``` ## The cookie The cookie is named after your project, so two Fenaura apps on the same domain cannot overwrite each other's sessions: `fenaura_eusid_`. On HTTPS it carries the `__Host-` prefix, which pins it to your exact host and forbids subdomains from planting a copy. It is set with: | Attribute | Value | Why | |---|---|---| | `HttpOnly` | yes | JavaScript cannot read it, so cross-site scripting cannot steal it | | `Secure` | on HTTPS | Never sent over a plain connection | | `SameSite` | `Lax` | Sent on top-level navigation, withheld from cross-site form posts | | `Path` | `/` | Available across the app | Because it is `HttpOnly`, the browser manages it. You never read the token from a cookie in your own code; you call `getUser()` and let the SDK do it. You can still see the cookie yourself: devtools, Application tab, Cookies. The value is an opaque session id, not a JWT, so there is nothing inside it to decode and nothing that can be forged from a stolen payload. ## Session lifetime Sessions last seven days and extend while they are used. An active user stays signed in; an abandoned session expires on its own. Signing out, or revoking a session from the dashboard, makes it stop working on the next request, not on next refresh. ```render img:docs-cookie-lifecycle|A session cookie is set at sign-in, slides forward at half its life while the user stays active, expires after seven idle days, and dies instantly on revoke ``` ## When cookies conflict If a request arrives with two session cookies that disagree, the platform refuses it: ``` 401 SESSION_CONFLICT Clear cookies for this site and sign in again. ``` This is deliberate. Accepting one of them silently is how you get a request that runs as the wrong end user, which is far worse than an error. It usually appears after deploying to a new domain, or after switching between a development and a production session in the same browser. ## Reading the session inside an edge function You do not parse anything. The platform has already resolved it, when the request arrives through your app's proxy (the session-gated path): ```ts export default async (req: Request, ctx: FenauraContext) => { return Response.json({ userId: ctx.user.userId, identifier: ctx.user.identifier, }); }; ``` `ctx.user` is `null` only on a route you have made public. On a private route, an unauthenticated request never reaches your handler. One exception to know: requests that arrive at the fleet URL directly (`edge.fenaura.dev/{token}/...`) carry no session by design. The URL token is the credential there, and `ctx.user` is empty. In development the dev key populates `ctx.user` with your own mirror identity instead. See [Your first function](/edge/first-function) for the two invocation paths. ### Do not write custom `session.ts` cookie or Bearer parsers You do **not** need a custom auth middleware (such as `session.ts` reading `c.env?.auth?.user`, `fenaura_eusid`, or `Authorization: Bearer`) inside your Edge Function: 1. **Already validated at the gateway**: Every private edge route passes through Fenaura's runtime session middleware before V8 runs. Forged, expired, cross-project, or wrong-environment tokens are rejected with `401` before your code ever executes. 2. **Sensitive headers are stripped & prefixed**: The gateway strips `cookie`, `authorization`, and `proxy-authorization` headers before invoking Hono, and browser cookies use project-scoped names (`fenaura_eusid_<12-hex>` or `__Host-fenaura_eusid_<12-hex>`). `c.env.auth` does **not** exist in Fenaura Edge (`ctx.env` holds your configured environment variables only, and `ctx.user` / `c.env.user` is the verified identity). 3. **Fallback `{ id: token }` patterns are dangerous**: Any helper that falls back to `if (!token) return null; return { id: token }` when `c.env?.auth?.user` is missing turns an unverified string into a trusted user ID if ever called on a `{ public: true }` route. Always treat `ctx.user` (`{ userId, identifier }`) as the single verified source of end-user identity. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [End-user management](/auth/end-users): revoke, block, delete. - [The context object](/edge/context): every `ctx` field. - [Troubleshooting](/auth/troubleshooting): what each auth error means. --- # End-user management URL: https://docs.fenaura.dev/auth/end-users Section: Authentication # End-user management End users belong to your project. The dashboard shows them, and lets you take action on one without writing code. Everything the dashboard does, the management API does too, so you can automate it. ## What you can see For each end user: their id, email, whether the email is verified, when they signed up, when they last signed in, whether they are blocked, the sessions they currently hold, and how they sign in. The auth method comes with the row: `password` for email-and-password accounts, or the provider name for OAuth accounts (`github`, `google`, and the rest), grouped as `social` versus `custom` so you can filter your own records by it. Users appear per environment. The development and production user lists are separate, and the dashboard shows the environment you currently have selected. ## Finding users Search by email. The list is paginated (`total`, `limit`, `offset` come back with every list response), so on a project with many users search rather than scrolling. Three list filters cover the states that are easy to miss: - By default the list hides accounts that are still waiting on a verification code. Pass `?status=unverified` to see only those, for example to clean up sign-ups that never confirmed. - `?status=all` shows every live account, including the unverified ones. - Deleted users are hidden too; `?includeDeleted=true` brings them back so you can find and restore one. ## Actions | Action | Effect | Reversible | |---|---|---| | Revoke | Kills the user's sessions **and** blocks new sign-ins. It is one action, not two. | Yes, Unblock | | Unblock | Lifts the block; the user can sign in again. Old sessions stay dead until they sign in. | Yes | | Kill all sessions | Every active session for the user stops working on the next request, without blocking the account. | They sign in again | | Approve / Unapprove | Development-only gate: with "Require approval for development users" on, an unapproved user's session is refused for data requests. See [Methods](/auth/methods#the-other-switch-require-approval-for-development-users). | Yes | | Restore | Undoes a soft delete | Yes | | Hard delete | Removes the row | **No** | Revoking is the right move when a device is lost or a token leaks: it costs the user a sign-in and nothing else. It is also the right move when you want the person gone for now: a revoked user cannot sign back in until you unblock them, and they are not told why. Telling an attacker they were blocked and telling a legitimate user the same thing are different problems, so the platform keeps the error neutral and you decide what your frontend says. Hard delete removes the row and cannot be undone. Take a backup first. ## What a blocked user sees A blocked end user fails sign-in with an error, and any session they already hold is refused on the next edge request. ## Your own account is there too The project owner appears in the end-user list as a mirror row, marked as the owner, in both environments. It exists so you can test the signed-in experience as yourself. You cannot revoke, block or delete it from the dashboard; the actions are refused for owner rows. ## Doing it from the API The management API covers the same ground for automation: ``` GET /management/projects/:projectId/end-users?status=all GET /management/projects/:projectId/end-users/:userId GET /management/projects/:projectId/end-users/:userId/sessions POST /management/projects/:projectId/end-users/:userId/sessions/revoke POST /management/projects/:projectId/end-users/:userId/sessions/kill-all POST /management/projects/:projectId/end-users/:userId/revoke POST /management/projects/:projectId/end-users/:userId/unblock POST /management/projects/:projectId/end-users/:userId/approve?env=development POST /management/projects/:projectId/end-users/:userId/unapprove?env=development POST /management/projects/:projectId/end-users/bulk-delete?env=development POST /management/projects/:projectId/end-users/import POST /management/projects/:projectId/end-users/:userId/restore DELETE /management/projects/:projectId/end-users/:userId ``` All of them take your management credentials, not an end-user session (on `https://api.fenaura.dev`, management routes sit under `/cp/management/...`). The approval and bulk-delete routes take `?env=development` (they exist for the development gate); the rest act on the environment in the query string (or `env` body field) the same way. Bulk-delete clears every pending development account at once when the approval queue is full. ## Bulk import (Supabase & bcrypt migration) Open **Users › Import users** in the dashboard or call `POST /management/projects/:projectId/end-users/import` (up to `1,000` users per request) with JSON (`{ users: [...] }`) or a raw CSV/JSON payload (`{ raw: "..." }`). Each row accepts `email`, `encrypted_password` or `password_hash` (`$2a$`, `$2b$`, `$2y$` bcrypt or `$argon2id$`), `password` (plaintext, hashed on import), `email_confirmed_at` / `email_verified_at` / `email_verified`, `raw_user_meta_data` / `metadata`, and `created_at`. Existing active emails in that environment are skipped automatically, and bcrypt hashes verify natively and upgrade transparently to Argon2id on first sign-in. See [Coming from Supabase](/coming-from-supabase) for the full export query. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Sessions and cookies](/auth/sessions): what revoking actually stops. - [Quotas](/platform/quotas): limits that apply to end users. --- # Troubleshooting authentication URL: https://docs.fenaura.dev/auth/troubleshooting Section: Authentication # Troubleshooting authentication Find the symptom, then the cause. Each entry names the thing that is actually wrong. ## `401 SESSION_CONFLICT` The request carried two session cookies that disagreed. **Fix:** clear cookies for the site and sign in again. This appears after deploying to a new domain, or after holding a development and a production session in the same browser. ## `401 UNAUTHORIZED` on a route you are sure is signed in Three candidates, in order of likelihood: 1. **The request has no session at all.** Check the browser's request headers for the cookie, or that your `curl` sends `Authorization`. 2. **The session was revoked.** Signing out elsewhere, or a revoke from the dashboard, kills it on the next request. 3. **The cookie is on the wrong domain.** A cookie set on `app.example.com` is not sent to `api.example.com`. ## Sign-in succeeds but `ctx.user` is null `ctx.user` is only `null` on a **public** route. If it is null on a route you believe is private, the route is declared public somewhere in the function config. Check the hoisted route list. ## `403 EMAIL_NOT_VERIFIED` The project requires verified emails. Send and confirm a code before signing in: ```ts await fenaura.auth.sendCode({ email, type: 'verification' }); await fenaura.auth.verifyCode({ email, code, type: 'verification' }); ``` Or turn off the requirement in auth settings while you develop. ## OAuth returns with no `code` The provider sends `code` only on success. No `code` means the user cancelled, or the callback URL is not registered on the provider's side for the environment you are using. ## `provider_not_configured` No client id and secret are stored for that provider. Add them in the project's auth settings. A provider configured in development is not configured in production, they are separate. ## The proxy files were written but calls fail You are probably calling `createClient('https://api.fenaura.dev', ...)` directly instead of `createClient('/fenaura', ...)`. The browser proxy only works when requests go through `/fenaura`. Import `fenaura` from `fenaura.ts` (see [Quickstart Step 4](/quickstart#4-call-createclient)). ## Password is rejected as too short The minimum is eight characters. There is no other rule, no required symbols, no required digits. ## A reset link does not work Reset is two steps and the second needs the code from the first. Opening the email's link signs nobody in; it takes you to a page where you submit the code with the new password. ## Still stuck Ask the agent inside the dashboard. It has the same knowledge as these docs plus the ability to read your project's configuration, which is usually what the problem is about. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Sessions and cookies](/auth/sessions): the credential model. - [Methods](/auth/methods): the correct call shapes. --- # Allowed origins URL: https://docs.fenaura.dev/auth/origins Section: Authentication # Allowed origins Your Project ID is not a secret. Anyone who reads your frontend code can copy it, and with it they can call sign-up on your project from their own site: create accounts, spend your email allowance, fill your Users tab. Allowed origins is the setting that decides whether that works. (Why the ID being public is acceptable at all: [Your Project ID is public](/platform/project-id).) Open it in the dashboard under **Domains** (`https://fenaura.dev/app/projects/your-project-id/domains`). [Open Allowed origins](https://fenaura.dev/app/projects/your-project-id/domains) ## The default: any origin is allowed Out of the box the allowlist is empty, and empty means **every origin is allowed**. That is a deliberate default, not a gap: it is what makes the quickstart work before you have decided where your app will live. localhost, a preview deployment, a renamed domain, all of them call your project and get answered. The cost of the default is the scenario above: your Project ID in someone else's page works too. Before you have real users, close it. ## Locking down Add your origins to the allowlist, one per line, as full origins including the scheme: ``` https://yourapp.com https://www.yourapp.com http://localhost:5173 ``` From the moment the list is non-empty, only those origins are served. A request from anywhere else fails with `ORIGIN_NOT_ALLOWED`, and the error names the calling origin so a legitimate user with a wrong subdomain is easy to diagnose. Two details that matter: - Origins are compared exactly: scheme, host and port. `https://app.com` and `https://www.app.com` are different origins; list both if you serve both. - localhost with its port counts as an origin, so `http://localhost:5173` is the entry for a Vite dev server, not `http://localhost`. - **Warn / remove `localhost` before production:** `localhost` (such as `http://localhost:5173`) is not unique to your machine. Anyone running a local dev server on that same port shares the origin and can call auth and data endpoints using your public Project ID, so keep `localhost` entries out of your production allowlist. ## The checks, in order Every request to auth, data and Fleet endpoints passes these gates, on every request, before your code runs: 1. **A disabled origin loses first.** If you switch an origin off in the dashboard without deleting it, requests from it are refused even while the allowlist is empty. This is the switch to use for a domain you are migrating away from. 2. **Cookie-carried requests must prove where they came from.** A request that carries your session cookie but arrives with no verifiable origin is refused with `ORIGIN_REQUIRED`, under any policy including the empty default. That is the teeth of the system: a script on another site cannot read or send your users' HttpOnly cookies, and a hand-built request cannot fake being their browser. 3. **A configured allowlist applies to every request.** Once the list is non-empty, cookie requests, bearer-token requests and public Fleet calls must all present a verifiable `Origin` or `Referer`. Browsers add `Origin` automatically. Servers and mobile clients can send a custom origin such as `app://my-backend` in the `Origin` header. Enforcement is not limited to cookie sessions. 4. **A broken allowlist fails closed and loudly.** If every entry on your list is unparseable, the platform refuses requests with `ORIGIN_CONFIG_MISSING` instead of silently serving nobody or silently serving everybody. A typo in the dashboard must never change the security posture by accident. ## What the check honestly is The calling origin is read **only from request metadata**: the `Origin` header, with a normalized `Referer` as fallback when `Origin` is absent. It is **never** read from the POST body, a query parameter, or a JSON field. Nothing you put in a request payload can claim an origin. A curl script can write any text it likes into an `Origin` header, so origin checking is not authentication for scripts and servers, and Fenaura does not pretend it is. Server-side requests authenticate with a secret key or a real session token instead. Fenaura also rejects an HTTP(S) `Origin` presented by a CLI-style User-Agent without browser Fetch Metadata headers (`Sec-Fetch-Site` and `Sec-Fetch-Mode`), so a spoofed header from curl fails even when its text matches your allowlist. An explicit `Origin: null` is refused whenever a policy is configured or cookies are carried. What the check defends against is the browser, which is the attack surface that matters. A browser will not let page JavaScript forge an `Origin` on a cross-site request, and it will not release your users' HttpOnly cookies to another site. The attacker who actually exists is someone else's webpage making your users' browsers call your API with their cookies attached, and that attacker runs into a check it cannot fake. A cookie-carrying request with no verifiable origin is refused under every policy, including the empty default. The gates run per request on the auth, data, realtime and Fleet planes, so no endpoint silently skips them. That is why server-to-server calls should use a secret key or session token and, when Allowed Origins is non-empty, an explicit custom origin such as `app://my-backend` in the `Origin` header. ```render img:docs-origin-check-flow|The origin checks run in order: origin presence for cookie requests, disabled origins, allowlist configuration, and the allowlist itself; each failure returns its own error code ``` ## Errors you will see | Code | Meaning | Fix | |---|---|---| | `ORIGIN_NOT_ALLOWED` | The calling origin is not on the allowlist | Add it under Domains | | `ORIGIN_DISABLED` | You explicitly disabled that origin | Re-enable it in Domains | | `ORIGIN_REQUIRED` | A cookie request arrived with no verifiable origin | Call from a browser fetch with `credentials: 'include'` | | `ORIGIN_CONFIG_MISSING` | The allowlist has no usable entries | Fix the entries and save | One difference worth knowing: Fleet (edge) routes answer a disabled or unlisted origin with a plain `404 NOT_FOUND` instead of these codes, so a probe cannot discover which origins a project has configured. The codes above are what the auth and data planes return. ## When to change it - **While building:** leave the allowlist empty. Everything works from anywhere, including localhost and preview deployments. - **Before launch:** add the origins you really serve. This is the setting that stops strangers signing people up with your Project ID. - **Migrating a domain:** add the new origin, then disable the old one rather than deleting it, so old clients get a clear refusal instead of silence. --- # Database overview URL: https://docs.fenaura.dev/database Section: Database # Database overview Every project gets its **own Postgres database**, a whole database, created when the project is, with its own owner role. Not a schema inside a database shared with other projects, and not a table prefix you have to remember to filter on. That distinction matters more than it sounds: - your tables cannot collide with another project's table names - you can create schemas, extensions and roles that are yours alone - a migration you run touches your database and nothing else - `\dt` lists your tables, not everyone's You reach it two ways, both already connected. **From the browser**, through the SDK query builder: ```ts const { data } = await fenaura.from('notes').select('*').limit(20).execute(); ``` **From an edge function**, either with Drizzle over `ctx.db`: ```ts const notes = await ctx.db.query.notes.findMany({ limit: 20 }); ``` or with raw SQL through `ctx.sql`: ```ts const notes = await ctx.sql`select * from notes limit 20`; ``` Use the builder for simple reads and writes, and raw SQL when a query is easier to express than to assemble. ## Tables Create and change tables in the dashboard's database page, or have the agent write a migration for you. Columns, indexes, defaults and constraints are all editable there. Sensitive columns can be marked, email addresses, phone numbers, tokens, and the platform masks them in logs, in tool output, and in the agent's view unless you explicitly ask for the value. ## Access control Two layers: 1. **Automatic.** Every edge route is session-gated, so an unauthenticated request never reaches your code and never touches the database. 2. **Row-level security.** Policies decide which rows a given end user may read or write. This is where "user A cannot see user B's notes" lives. See [Security and RLS](/database/security). ## Limits worth knowing | Limit | Value | |---|---| | Rows per query response | 1000 | | Items in an `in()` list | 100 | | Concurrent writes | Guarded by Postgres; use `upsert` for idempotence | A query asking for more than 1000 rows is capped at 1000. Page with `range` or `limit`/`offset` rather than expecting one huge response. ## Next - [Querying](/database/querying): the builder. - [Filtering](/database/filtering): every operator. - [Security and RLS](/database/security): policies and sensitive columns. --- # Querying URL: https://docs.fenaura.dev/database/querying Section: Database # Querying The builder chains calls and returns `{ data, error }`. Learn one rule about when a chain runs and the rest follows. ## When a chain runs | Call | Runs | |---|---| | `insert` | Immediately | | `upsert` | Immediately | | `.single()` / `.maybeSingle()` | Immediately | | `update` | Only with `.execute()` or a terminal | | `delete` | Only with `.execute()` or a terminal | | `select` | Only with `.execute()` or a terminal | An `update` chain that is awaited but never terminated does nothing, silently. That is the single most common mistake with this builder. These docs always show `.execute()` so the rule cannot bite you. ## What comes back Every finished chain resolves to the same envelope, so one check covers the whole builder. A successful query looks like this: ```json { "status": "success", "data": [ { "id": "...", "title": "Hello", "created_at": "..." } ], "count": 1, "request_id": "req_..." } ``` A failed one carries the reason instead of the rows: ```json { "status": "error", "data": null, "error": { "code": "QUERY_FAILED", "message": "Query failed" }, "request_id": "req_..." } ``` `count` appears when you asked for it (`.count('exact')` or `head: true`); `request_id` is the id to quote when something misbehaves and you are reading logs or asking support. `error.code` is stable machine text, `error.message` is for showing. Writes return the same envelope with the affected row in `data` instead of an array. The `{ data, error }` pair your code destructures is this envelope with the wrapping removed; the JSON above is what travels over the wire. ```ts // Nothing happens await fenaura.from('notes').update({ title: 'New' }).eq('id', id); // Correct await fenaura.from('notes').update({ title: 'New' }).eq('id', id).execute(); ``` ## Select ```ts const { data, error } = await fenaura .from('notes') .select('id, title, created_at') .execute(); ``` `'*'` selects every column. Name columns explicitly for anything that will run often, it is smaller over the wire and it does not break when you add a column of sensitive data. ```ts // Nested relationships const { data } = await fenaura .from('notes') .select('id, title, author:users(id, display_name)') .execute(); ``` ## Insert ```ts const { data } = await fenaura .from('notes') .insert({ title: 'First note', body: 'Hello' }) .execute(); ``` One object inserts one row; an array inserts many. Upsert refuses arrays, send one row per call when you need upsert semantics. ## Update ```ts await fenaura.from('notes').update({ title: 'Renamed' }).eq('id', id).execute(); ``` An update with no filter is refused rather than applied to every row. Add `.eq()`, `.in()` or another filter. ## Delete ```ts await fenaura.from('notes').delete().eq('id', id).execute(); ``` Same rule: no filter, no delete. ## Upsert ```ts await fenaura .from('notes') .upsert({ id, title: 'Draft' }, { onConflict: 'id' }) .execute(); ``` Idempotent by design: run it twice and the second run updates instead of failing. Use it for anything a retry might replay. ## Single rows ```ts const { data, error } = await fenaura.from('notes').select('*').eq('id', id).single(); ``` `.single()` errors when there is no row or more than one. `.maybeSingle()` returns `data: null` when there is no row and errors only on more than one. Prefer `.maybeSingle()` when "not found" is a normal outcome. ## Counting ```ts const { count } = await fenaura .from('notes') .select('*', { count: 'exact', head: true }) .execute(); ``` `head: true` returns the count without the rows, which is much cheaper than fetching and measuring. ## Pagination ```ts const page = 2; const size = 20; const { data } = await fenaura .from('notes') .select('*') .order('created_at', { ascending: false }) .range((page - 1) * size, page * size - 1) .execute(); ``` `range` is inclusive on both ends. For a feed that grows while the user scrolls, page by a stable key (a timestamp plus id) rather than by offset, or rows will repeat and skip. ## Ordering ```ts .order('created_at', { ascending: false }) .order('title', { ascending: true, nullsFirst: false }) ``` ## Next - [Filtering](/database/filtering): every operator. - [Drizzle in the edge](/database/drizzle): the server-side style. --- # Filtering URL: https://docs.fenaura.dev/database/filtering Section: Database # Filtering Filters are methods on the chain. Each one takes a column and a value. ## Comparison ```ts .eq('status', 'published') // status = 'published' .neq('status', 'draft') // status <> 'draft' .gt('views', 100) // views > 100 .gte('views', 100) // views >= 100 .lt('views', 100) // views < 100 .lte('views', 100) // views <= 100 ``` ## Null and boolean ```ts .is('deleted_at', null) // deleted_at is null .is('published', true) // published = true ``` `is` is for `null` and booleans only. For everything else use `eq`. ## Sets ```ts .in('status', ['draft', 'published']) // status in (...) .not('status', 'in', ['archived']) // status not in (...) ``` An `in` list is capped at 100 items. For a longer list, use a join or a temporary table instead of a bigger list. ## Text ```ts .like('title', 'Hello%') // case-sensitive, % and _ are wildcards .ilike('title', 'hello%') // case-insensitive ``` ```ts .textSearch('body', 'postgres') // full-text search ``` `ilike` is the usual choice for a search box. `textSearch` is for real full-text search with stemming and ranking; use it when the column has a text index. ## JSON and arrays ```ts .contains('tags', ['featured']) // array or JSON contains .containedBy('tags', ['a', 'b', 'c']) .overlaps('tags', ['urgent', 'later']) ``` `contains` asks "does it have all of these", `overlaps` asks "does it have any of these", and `containedBy` asks "is it entirely inside this set". ## Combining Filters on one chain are combined with AND: ```ts const { data } = await fenaura .from('notes') .select('*') .eq('owner', userId) .eq('status', 'published') .gte('views', 10) .execute(); ``` That is `owner = ? and status = ? and views >= ?`. ## OR ```ts const { data } = await fenaura .from('notes') .select('*') .or('status.eq.draft,status.eq.published') .execute(); ``` The string form is `column.operator.value`, comma-separated. ## Negating ```ts .not('status', 'eq', 'archived') .not('title', 'ilike', '%test%') ``` `not` wraps any operator. ## Wildcards that bite Inside `like` and `ilike`, `%` matches any run of characters and `_` matches one. A user-typed search containing `%` will match far more than they meant. Escape it before building the pattern: ```ts const safe = term.replace(/[%_\\]/g, '\\$&'); .ilike('title', `%${safe}%`) ``` ## Performance A filter on an indexed column is fast. A filter with `ilike '%term%'` cannot use a normal index, because the wildcard is at the front. For a large table, add a trigram index or switch to `textSearch`. ## Next - [Querying](/database/querying): ordering and pagination. - [Security and RLS](/database/security): why filters are not your only defence. --- # Drizzle in the edge URL: https://docs.fenaura.dev/database/drizzle Section: Database # Drizzle in the edge Inside an edge function the database is ready. There is no connection string to load, no pool to create, and no teardown, the runtime owns the connection. ```ts export default async (req: Request, ctx: FenauraContext) => { const notes = await ctx.db.query.notes.findMany({ where: (t, { eq }) => eq(t.owner, ctx.user!.userId), limit: 20, }); return Response.json({ notes }); }; ``` ## ctx.db `ctx.db` is a Drizzle client with your project's tables in scope as `ctx.db.query.
`. ### findMany ```ts const rows = await ctx.db.query.notes.findMany({ where: (t, { eq, and, gte }) => and(eq(t.owner, userId), gte(t.views, 10)), orderBy: (t, { desc }) => desc(t.created_at), limit: 20, offset: 0, with: { author: true }, // relations, if defined }); ``` ### findFirst ```ts const note = await ctx.db.query.notes.findFirst({ where: (t, { eq }) => eq(t.id, id), }); ``` `findFirst` returns the row or `undefined`, which reads more naturally than destructuring an array of one. ### insert, update, delete ```ts await ctx.db.insert(notes).values({ title: 'New note', owner: userId }); await ctx.db.update(notes).set({ title: 'Renamed' }).where(eq(notes.id, id)); await ctx.db.delete(notes).where(eq(notes.id, id)); ``` The Drizzle forms here do run when awaited; the "needs a terminal" rule belongs to the browser builder, not to `ctx.db`. ## ctx.sql For anything easier to write as SQL: ```ts const rows = await ctx.sql` select id, title from notes where owner = ${userId} order by created_at desc limit 20 `; ``` Tagged-template values are parameterised, not interpolated. Never build SQL by concatenating a value into the string, that is how injection gets in. ```ts // Never do this await ctx.sql`select * from notes where title = '${term}'`; // Do this await ctx.sql`select * from notes where title = ${term}`; ``` ## Transactions are not available The edge database client is a proxy driver, and it does not support `ctx.db.transaction()`. Calling it throws: ``` Transactions are not supported by the Postgres Proxy driver ``` This is a real limitation, not a style preference. Write around it rather than assuming a rollback you will not get. **For a multi-row write that must be atomic,** send it as one SQL statement. A single `insert ... values (...), (...)` or an `update` with a `case` is atomic on its own: ```ts await ctx.sql` insert into ledger (account, amount) values (${from}, -100), (${to}, 100) `; ``` **For work that must be idempotent,** give it a key and let a unique constraint do the guarding: ```ts await ctx.db.insert(payments) .values({ idempotency_key: key, amount }) .onConflictDoNothing(); ``` A second attempt with the same key inserts nothing, so a retried request cannot charge twice. **For multi-step logic,** order the writes so a failure is recoverable, write the intent row first, then the effect, and let a later request finish anything left half-done. This is the ordinary outbox pattern, and it survives a crash in a way an in-memory transaction never could. Do not build on `ctx.db.transaction`. It will not run. ## Which to use | Reach for | When | |---|---| | `ctx.db` | You want types, and the query is a normal read or write | | `ctx.sql` | Aggregates, window functions, CTEs, or a query clearer as SQL | Both run on the same connection and see the same data. Mixing them in one function is fine. ## The full Drizzle language The pages here cover how the client is handed to you. The query language itself is Drizzle's, so for schemas, relations, `with`, transactions, prepared statements and typed selects, read [orm.drizzle.team](https://orm.drizzle.team). A Fenaura Fleet runs real Drizzle, the documentation there applies as written, because nothing about the API has been changed. ## Next - [Migrations](/database/migrations): how schema changes ship. - [Security and RLS](/database/security): policies. --- # Migrations & schema changes URL: https://docs.fenaura.dev/database/migrations Section: Database # Migrations & schema changes Fenaura separates **schema** (structure) from **data** (rows), and keeps your Development and Production databases isolated. ## Development and Production are decoupled DDL you run in Development (`CREATE TABLE`, `ALTER TABLE`, `DROP COLUMN`, indexes, constraints, RLS policies, triggers) stays strictly in Development. Nothing is auto-mirrored to Production. That isolation prevents three common production failures: 1. A `DROP COLUMN` or `DROP TABLE` during development cannot delete live customer data in Production. 2. Schema edits in development cannot take an `ACCESS EXCLUSIVE` lock on a busy Production table. 3. Half-finished schema changes cannot crash Production code mid-iteration. ## Where to open it Use [Database › Promote](/app/projects/:projectId/database/promote) to move a structure in either direction. The [Migrations (Sync)](/app/projects/:projectId/database?sub=migrations) tab shows the comparison and the history of promotions and rebases. The sync badge at the upper right is green (`#22c55e`) when the structures match, gold (`#f59e0b`) when one side is ahead and a direction is offered, and red (`#ff3b30`) when both sides changed or the diff is destructive. ## How promotion compares and applies changes When you promote from Development to Production, Fenaura does **not** replay a brittle history log or copy any table rows. Instead, it inspects the live PostgreSQL catalogs (`pg_class`, `pg_attribute`, `pg_constraint`, `pg_index`, `pg_policy`, `pg_trigger`) in both databases and computes a structural diff. - **Data never moves.** `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE`, `GRANT`/`REVOKE`, and `CREATE EXTENSION` are never part of schema promotion. Your Production rows stay untouched. - **Idempotent when in sync.** If Production's structure already matches Development, promotion makes zero changes and reports that both are in sync. - **Risk classification.** Every diff is classified as `safe`, `warning` (lock or table-rewrite hazards such as type changes or `SET NOT NULL`), or `destructive` (`DROP TABLE` or `DROP COLUMN`). - **Transactional with lock timeouts.** Promotion runs inside a single `BEGIN` ... `COMMIT` transaction on Production with `lock_timeout = '5s'` and `statement_timeout = '30s'`. If Production cannot acquire the lock within 5 seconds or a statement exceeds 30 seconds, the transaction rolls back cleanly without leaving partial changes or blocking traffic indefinitely. ## How dropping a column in Development works Dropping a column in Development: ```sql ALTER TABLE users DROP COLUMN legacy_plan; ``` only removes `legacy_plan` from your **Development** database. Production still has `legacy_plan` and all of its customer values. When you later open **Promotion** to push Development's structure to Production: 1. The structural diff detects the missing column and generates `ALTER TABLE public.users DROP COLUMN IF EXISTS legacy_plan;`. 2. It marks the diff as `destructive` with an explicit warning listing the table and column that will be destroyed. 3. Fenaura requires **project admin** rights and returns `CONFIRMATION_REQUIRED` with the warning list. Nothing runs until you confirm with a single-use confirmation token. If you did not intend to drop that column in Production, re-add it in Development before promoting. ## The safe order for breaking changes Even with transactional safety and confirmation gates, removing or renaming live columns should happen in stages so running app code never queries a missing column: 1. **Add** the new column (nullable or with a `DEFAULT`) in Development and promote. 2. **Deploy app code** that writes to both (or only the new column) and reads from the new column. 3. **Backfill** existing Production rows if needed. 4. **Drop** the old column in Development and promote with the confirmation token once old code is no longer running. ## Adding a `NOT NULL` column safely ```sql ALTER TABLE notes ADD COLUMN status text; -- 1. nullable UPDATE notes SET status = 'draft' WHERE status IS NULL; -- 2. backfill ALTER TABLE notes ALTER COLUMN status SET NOT NULL; -- 3. constrain ``` Or add it with a `DEFAULT`: ```sql ALTER TABLE notes ADD COLUMN status text NOT NULL DEFAULT 'draft'; ``` ## Indexes without blocking writes ```sql CREATE INDEX CONCURRENTLY notes_owner_idx ON notes (owner); ``` `CONCURRENTLY` builds the index without holding a write lock across the whole table. ## Next - [Promotion, worked example](/database/promotion): step-by-step walkthrough. - [Security and RLS](/database/security): how policies are promoted with tables. - [Drizzle in the edge](/database/drizzle): querying the updated schema. --- # What Row Level Security protects URL: https://docs.fenaura.dev/database/rls Section: Database # What Row Level Security protects Row Level Security (RLS) is the reason two users of your app cannot read each other's rows even though they talk to the same database with the same credentials. It is the single most important safety property of the data path, so it is worth understanding what it actually does rather than treating it as a checkbox. ## The question people actually ask *"If my front-end calls the database directly, can user A read user B's rows?"* No, as long as the table has RLS enabled with a policy that scopes rows to the current user. That is the whole purpose. The front-end never holds a credential that could read everything: the request carries a session, and the database restricts what that session may see. If a table has **no** RLS, then a request through the data API can read and modify every row. That is why Fenaura refuses to let you turn RLS off. ## RLS is mandatory `ALTER TABLE ... DISABLE ROW LEVEL SECURITY` is rejected by the platform with `RLS_LOCKED`. You cannot disable it, and you cannot force it off with `FORCE ROW LEVEL SECURITY` either. This is not a default that you may dislike; it is a guardrail. Two places enforce the same rule from different directions: - **The SQL editor** refuses the statement before anything runs. - **The table builder** always emits `ENABLE ROW LEVEL SECURITY` when it creates a table and has no off switch. After creating a table it verifies RLS really is on, and if verification fails it rolls the creation back with `RLS_VERIFICATION_FAILED` rather than leaving you a table that looks fine and is not. ## How a request proves who it is When a request reaches your database, the runtime tells Postgres which user it is acting as, per request, and resets that identity when the connection goes back to the pool. That last part matters more than it sounds: a pooled connection that kept its previous tenant's identity would let the next request run as the tenant before it. The runtime resets the role, the search path, the statement timeout and the current user on **every** exit path, including an error and a panic, and not just on success. So a policy is not trusting something the client sent. It is comparing rows against an identity the runtime established for that request. ## Seeing a problem before your users do The advisors check for the failure mode that quietly defeats RLS: **policies exist on a table but RLS is disabled, so they never apply.** The advisor reports that table explicitly, because the policies being present makes it look safe when it is not. If you ever see that warning, the table is readable by any request that can reach it. Enabling RLS is the fix, and the SQL editor will not let you do the opposite. ## The honest limits - RLS protects the **data API path**. Code that runs with a database role that bypasses RLS is not protected by it, by definition. Your Fleets functions connect with the project's own role, so treat any endpoint you write as a place where you do the checking yourself. - RLS does not stop a bug in your own policy. A policy written as `USING (true)` allows everything and is still "RLS enabled". The advisor can tell you RLS is off; it cannot tell you your policy is too wide. Read your policies. - RLS does not encrypt anything. It decides which rows a session may reach, not what those rows contain. For the mechanics of writing a policy, see [Security and access](#docs/database/security), and for running `CREATE POLICY` statements interactively see the [SQL editor](#docs/database/sql-editor). --- # Security and RLS URL: https://docs.fenaura.dev/database/security Section: Database # Security and RLS Two independent layers protect your data: the gateway validates the user's session before any private handler runs, and PostgreSQL Row-Level Security (RLS) enforces which rows a caller can read or write. Every table created in Fenaura starts with **RLS enabled by default**. While RLS is on with **0 policies**, direct Data API queries deny all rows (`0` returned), while your server Fleets (`ctx.db`) keep full access behind the trust boundary. ## Pick a policy template (no SQL required) When creating a table or managing an existing table (**Database › Table Editor › Manage Policies**), open the **Policy Template** dropdown to apply battle-tested PostgreSQL rules in one click: | Template | Operations allowed | Best for | |---|---|---| | `Users manage own rows (CRUD)` | `SELECT`, `INSERT`, `UPDATE`, `DELETE` where `= (SELECT auth.uid())` | Private notes, todos, user settings, saved items | | `Users read own rows` / `insert` / `update` / `delete` | Single operation restricted to `= (SELECT auth.uid())` | Invoices, orders, audit history where users can only read or insert their own | | `Anyone can read, owners write` | Public `SELECT` (`true`) + owner-only `INSERT`, `UPDATE`, `DELETE` | Public profiles, blog posts, comments, listings | | `Anyone can read (Public SELECT)` | Open `SELECT` (`USING (true)`) | Public catalogues, documentation, landing-page content | | `Signed-in users can read` / `full access` | Requires valid session (`(SELECT auth.uid()) IS NOT NULL`) | Shared workspace tables accessible to any signed-in user | | `Custom rule builder` | Choose operation, access rule, column match, and policy name | Custom policy names or single-operation combinations | | `No policies (Deny Data API)` | 0 policies added | Server-only tables accessed strictly through Fleets (`ctx.db`) | For per-user templates, Fenaura lets you pick which column holds the user ID (`owner`, `user_id`, etc.) and generates the canonical `(SELECT auth.uid())` policy expression for Postgres automatically. If a table still has RLS enabled with 0 policies when you leave or close the policy editor, Fenaura shows a quick reminder with shortcuts to **Add policy** or **Continue anyway** (plus an account-level "Do not show again" option saved on the backend). ## Writing policies in SQL Every visual template compiles down to standard PostgreSQL `CREATE POLICY` statements using `auth.uid()` (which reads the verified end-user UUID from the Data API connection): ```sql -- Read your own rows create policy allow_owner_select on public.notes for select using ((owner = (select auth.uid()))); -- Insert only rows tagged with your own user ID create policy allow_owner_insert on public.notes for insert with check ((owner = (select auth.uid()))); -- Update only your own rows, and prevent reassigning owner away create policy allow_owner_update on public.notes for update using ((owner = (select auth.uid()))) with check ((owner = (select auth.uid()))); ``` `USING` filters which existing rows can be read, updated, or deleted. `WITH CHECK` validates new or updated row values. Include both on `UPDATE` so callers cannot transfer row ownership to another user. ## Client filters are convenience, not defence If client code sends `.eq('owner', userId)`, that filter helps honest callers fetch less data. Someone calling your endpoint or Data API directly can remove that filter. Always let RLS (on Data API tables) or server-side filtering (in Fleets) enforce ownership. ## Server Fleets vs Data API | Plane | Database connection | When RLS applies | |---|---|---| | **Data API / Client SDK** | Connects as restricted API role with session `auth.uid()` set | **Enforced automatically on every query** | | **Fleets (`ctx.db`)** | Connects as the project's owner role behind the trust boundary | Bypassed, so always filter by `ctx.user.userId` in code | Inside a Fleet endpoint, private routes already reject unauthenticated calls with `401` before your code runs, so scope queries directly by `ctx.user.userId`: ```ts const notes = await ctx.db.query.notes.findMany({ where: (t, { eq }) => eq(t.owner, ctx.user.userId), }); ``` ## Sensitive columns Mark password hashes, private tokens, phone numbers, or other sensitive columns as **Sensitive** in the Table Editor: - Encrypted at rest with AES-256-GCM when written through Table Builder - Masked automatically in agent tool output and logs so transcripts never leak secrets ## Quick checklist - [ ] RLS enabled on every table exposed to client queries - [ ] Appropriate template or per-operation policy attached (`UPDATE` covers both `USING` and `WITH CHECK`) - [ ] Every Fleet query filtered by `ctx.user.userId` - [ ] Sensitive columns marked encrypted/masked - [ ] Access verified by calling the API directly as two different users ## Next - [Migrations](/database/migrations): shipping schema and policy changes safely. - [Sessions and cookies](/auth/sessions): how `ctx.user` and `auth.uid()` resolve. --- # SQL editor URL: https://docs.fenaura.dev/database/sql-editor Section: Database # SQL editor The SQL editor runs arbitrary SQL against your project's Postgres database. It is a real client, not a toy box: multiple tabs, persisted history, saved snippets, schema autocomplete, and per-statement results for a whole script. [Open the SQL editor](https://fenaura.dev/app/projects/your-project-id/sql) That deep link opens the editor for whichever project you have open. ## Which database it talks to The editor follows the environment switch in the header, exactly like the rest of the dashboard. In **Development** your statements hit the development database; in **Production** they hit production. The two are different physical databases, so a `SELECT` you ran in development proves nothing about production and a `DROP` in production cannot be undone by switching back. The hint above the editor always names the environment you are connected to. Read it before you run anything that writes. ## Running a script, not just a statement You can paste a whole script and run it in one go. The server splits it correctly, including semicolons inside strings, quoted identifiers and dollar-quoted function bodies, so a `CREATE FUNCTION ... $$ ... $$` does not get cut in half. A batch runs in **one transaction with a savepoint per statement**. That has two consequences you can rely on: - If statement 12 of 40 fails, execution **stops there** and the whole batch rolls back. You get "stopped at statement 12 of 40", not 40 half-applied changes. - Results are reported **per statement**, in execution order, under a summary line such as "37 of 39 succeeded". Statements after the failure are labelled *not run*, so you can see exactly where the script stopped. An idempotent re-run is not an error. `CREATE TABLE IF NOT EXISTS` on a table that already exists, or a `CREATE EXTENSION` that is already installed, comes back as a success with a notice rather than a failure. ## Reading results Large `SELECT`s are paginated automatically: the editor wraps your query and fetches one page at a time, so a million-row table does not try to render a million rows. When a result is truncated you get an explicit notice rather than a silently short list. For writes, the result row reports **rows affected** instead of returning a result set. You do not have to guess whether the `UPDATE` matched anything. ## Tabs, history and snippets - **Tabs** keep several queries open at once. Each tab holds its own document, so switching tabs does not lose what you typed. - **History** records what you ran, when, and how long it took, and survives a reload. - **Snippets** save a query under a name you can insert again. ## Autocomplete The editor loads your schema and completes table and column names as you type. It reads the real catalog, so it completes what exists, not what the docs say should exist. ## Safety rails The editor is powerful, and a few guards sit in front of destructive work: - **Structure changes are detected** before running. The editor classifies statements the same way the server's schema mirror does, so the warning you see matches what the server is about to do. - **Destructive statements** (`DROP TABLE`, `DROP COLUMN`, `DROP POLICY` and friends) ask for confirmation first. - **A blocking firewall** rejects statements the platform does not allow at all (`FORBIDDEN_STMT`, `FORBIDDEN_SCHEMA`, `FORBIDDEN_FUNCTION`, `SQL_NOT_ALLOWED`). Nothing executes in that case, and the statements around the rejected one are marked *not run*. - **Oversized batches** are refused up front: more than 300 statements, or a payload over 1 MB. Two guards are worth naming because they are not negotiable: - **Row Level Security cannot be turned off.** `ALTER TABLE ... DISABLE ROW LEVEL SECURITY` is refused with `RLS_LOCKED`. RLS is mandatory on Fenaura; see [What Row Level Security protects](#docs/database/rls) for why. - **The `users` table is protected.** You cannot drop it, or drop or rename its `id` and `email` columns, in either environment. The attempt fails with `PROTECTED_USERS_COLUMN_LOCKED` rather than leaving your auth table unrecognisable. ## What runs where Most statements go straight to your database. Structure changes also go through the schema mirror, because Fenaura keeps the development and production schemas aligned so promotion behaves predictably. If you want the full story on how a schema change travels from development to production, read [Environments](/environments) and [Promotion](/database/promotion) next. --- # External Postgres & Redis URL: https://docs.fenaura.dev/database/external-connections Section: Database # External Postgres & Redis (Platform secrets) When you run your own backend outside Fenaura Fleets (Express, Fastify, Next.js server actions, FastAPI, Django, Go, Rust, Java, Laravel, or anything else), you do **not** install a proprietary Fenaura backend SDK or learn Fenaura database syntax. You connect directly to Postgres and Redis with normal language drivers using the credentials under **Secrets** in the project sidebar. The **Database** page shows the live connection facts (host, port, user, SSL) for the selected environment. The **Redis** page is the key browser and command console. Full connection strings and rotation stay under **Platform secrets**. **Strict environment isolation:** Development and Production have completely separate credentials, roles, and databases. If you copy credentials while **Development** is selected, they connect strictly to your Development database (never Production). If you copy credentials while **Production** is selected, they connect strictly to your Production database (never Development). ## Platform secrets vs Environment variables Under the **Secrets** menu in your project navigation, there are two pages: | Page | Purpose | |---|---| | **Platform secrets** (`/secrets`) | Managed per-environment **PostgreSQL** and **Redis TLS** connection strings, hosts, ports, users, passwords, live database/Redis usage meters, and one-click rotation. | | **Environment variables** (`/env`) | Your own custom secrets (`STRIPE_SECRET_KEY`, `RESEND_API_KEY`, etc.) and custom encrypted `project_secrets` injected into Fenaura Fleets via `ctx.env`. | All credentials in **Platform secrets** switch automatically between **Development** and **Production** using the environment selector in the header. ## PostgreSQL connection variables From **Secrets › Platform secrets**, copy either the single `DATABASE_PUBLIC_URL` or individual `PG*` fields: | Variable | Value / format | |---|---| | `PGHOST` | Shown live in **Secrets › Platform secrets** (the project API host, port `5432`) | | `PGPORT` | `5432` | | `PGUSER` | Environment-scoped tenant role (`pdb__prod` / `pdb__dev`) | | `PGPASSWORD` | Encrypted per-environment password (rotatable with zero shared access) | | `PGDATABASE` | Isolated project database (`pdb_` or `pdb__test`) | | `PGSSLMODE` | `require` | | `DATABASE_URL` | `postgresql://:@:5432/?sslmode=require` | | `DATABASE_PUBLIC_URL` | Same TLS URL ready for external apps, CI, and `psql` / `pg_dump` | TLS (`sslmode=require`) is enforced on external Postgres connections (`5432`), and each tenant role is isolated strictly to its own database with `CONNECTION LIMIT 20`. Copy the exact URL and host from **Secrets › Platform secrets** instead of constructing them by hand. ### Connection budget: is 20 enough? `CONNECTION LIMIT 20` counts simultaneous Postgres sessions for your project role. It is not a rate limit. One persistent backend with a shared application-side pool of 5 to 10 connections is comfortably inside it. You will hit it if you open a new connection per HTTP request, or if many serverless instances each keep a 10-connection pool alive. Create the pool once at module scope, share it for the life of the process, and keep the total across all your processes below 20. If you need more concurrent clients, put **PgBouncer** in `transaction` mode in front of the database, or use a server-side pooler, and remember that your application pool and the server pooler share the same budget. For comparison, Supabase's free (Nano) compute has 60 database connections, 200 pooler clients, and a default server-side pool size of 15. Its shared transaction pooler exists because short-lived serverless connections otherwise exhaust the direct limit. Fenaura's 20 sits in the same practical class: a modest pooled budget that works well when your driver pools connections rather than opening one per request. ### Pooling & PgBouncer compatibility Because external clients connect straight to PostgreSQL over TLS on port `5432` (no proprietary middleware sits in the wire protocol), any standard Postgres driver, ORM pooler, Prisma Accelerate/pool, or self-managed **PgBouncer** (`pool_mode=transaction` or `session`, `sslmode=require`) works cleanly as long as total concurrent connections from your app stay within your project's 20-connection budget. ### Client examples ```ts // Node.js (pg v8+) + Drizzle ORM import { Pool } from 'pg'; import { drizzle } from 'drizzle-orm/node-postgres'; // Copied from Secrets > Platform secrets (DATABASE_PUBLIC_URL) const DATABASE_PUBLIC_URL = 'postgresql://role:password@db.fenaura.dev:5432/project_db?sslmode=require'; const dbUrl = new URL(DATABASE_PUBLIC_URL); dbUrl.searchParams.delete('sslmode'); // pg v8.13+ overrides `ssl` if ?sslmode=require stays in the URL const pool = new Pool({ connectionString: dbUrl.toString(), ssl: { rejectUnauthorized: false }, // encrypted TLS channel over 5432 max: 10, }); export const db = drizzle(pool); ``` ```python # Python (psycopg / SQLAlchemy) import psycopg # Copied from Secrets > Platform secrets (DATABASE_PUBLIC_URL) DATABASE_PUBLIC_URL = "postgresql://role:password@db.fenaura.dev:5432/project_db?sslmode=require" with psycopg.connect(DATABASE_PUBLIC_URL, sslmode="require") as conn: with conn.cursor() as cur: cur.execute("SELECT id, title FROM notes ORDER BY created_at DESC LIMIT 20") rows = cur.fetchall() ``` ```prisma // prisma/schema.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL_PRISMA") } ``` ```env # Copy DATABASE_URL_PRISMA from Secrets > Platform secrets. # The TLS certificate is self-signed: sslaccept=accept_invalid_certs keeps # Prisma connecting without disabling encryption. Keep DATABASE_URL for psql, # node-pg and Drizzle. DATABASE_URL_PRISMA="postgresql://user:password@:5432/?sslmode=require&sslaccept=accept_invalid_certs" ``` ```go // Go (pgxpool): copied from Secrets > Platform secrets pool, err := pgxpool.New(ctx, databasePublicURL) if err != nil { return err } defer pool.Close() row := pool.QueryRow(ctx, "SELECT NOW()") ``` ## Redis TLS connection variables From **Secrets › Platform secrets**, Fenaura provisions a dedicated TLS-encrypted Redis database per environment: | Variable | Notes | |---|---| | `REDISHOST` | Shown live in **Secrets › Platform secrets** (the project API host, port `6380`) | | `REDISPORT` | `6380` (TLS) | | `REDISUSER` | Dedicated Redis user: `fnr_<32hex>_prod` or `fnr_<32hex>_dev` | | `REDISPASSWORD` | Rotatable 256-bit credential | | `REDIS_URL` / `REDIS_PUBLIC_URL` | `rediss://:@redis.fenaura.dev:6380` | ### TTL, quotas, and usage - **A real Redis database:** every environment gets its own TLS-encrypted Redis database. Use normal commands (`GET`, `SET`, `MGET`, `INCR`, `SCAN`, hashes, lists, sets, sorted sets, counters) with any standard client. - **30-day maximum TTL:** Keys cannot persist permanently; `PERSIST` is blocked and TTLs are capped at 30 days (`2,592,000` seconds). - **Safe command surface & quotas:** Server administration and unsafe commands (`FLUSHDB`, `FLUSHALL`, `CONFIG`, `ACL`, `CLIENT`, `SCRIPT`, `EVAL`, `CLUSTER`, `BGSAVE`, `SELECT`) are rejected cleanly while the standard command surface works normally within your project's 100 MiB quota. - **Usage:** the **Redis** page shows live memory, key count, reads/writes, external commands, and network bytes for the selected environment. ### Redis client examples ```ts // Node.js (ioredis) import Redis from 'ioredis'; // Copied from Secrets > Platform secrets (REDIS_PUBLIC_URL) const REDIS_PUBLIC_URL = 'rediss://user:password@redis.fenaura.dev:6380'; export const redis = new Redis(REDIS_PUBLIC_URL, { tls: { rejectUnauthorized: false }, }); await redis.set('cache:user:42', JSON.stringify({ plan: 'pro' }), 'EX', 3600); const val = await redis.get('cache:user:42'); ``` ```python # Python (redis-py) import ssl, redis # Copied from Secrets > Platform secrets (REDIS_PUBLIC_URL) REDIS_PUBLIC_URL = "rediss://user:password@redis.fenaura.dev:6380" r = redis.from_url( REDIS_PUBLIC_URL, ssl_cert_reqs=ssl.CERT_NONE, decode_responses=True, ) r.setex("cache:user:42", 3600, "ok") print(r.get("cache:user:42")) ``` ## Rotating credentials Click **Rotate password** on either the PostgreSQL or Redis card inside **Secrets › Platform secrets**: - **PostgreSQL:** Issues a fresh random password, alters your project database role (`ALTER ROLE`), updates the encrypted platform secret, and resets active internal pools immediately. - **Redis:** Mints a new 256-bit password, stores the encrypted hash, and disconnects existing external sockets using the revoked credential so old clients cannot continue issuing commands. ## Next - [Backend auth implementation](/backend-auth-implementation): pair custom backends with Fenaura Auth (`browser_flow: false`). - [Coming from Supabase](/coming-from-supabase): stream `pg_dump` directly with `DATABASE_PUBLIC_URL`. - [SQL editor](/database/sql-editor): inspect tables and run migrations in the browser. --- # Postgres functions URL: https://docs.fenaura.dev/database/functions Section: Database # Postgres functions Some logic belongs in the database itself: a leaderboard rank, a counter update, a query too intricate for the query builder. Write it as a Postgres function and call it from the SDK with `rpc()`. ## Writing the function Create it in the dashboard's SQL editor, in the `public` schema: ```sql create function add_score(p_player uuid, p_points int) returns table (player uuid, total int) language sql stable as $$ insert into scores (player, points) values (p_player, p_points); select p_player, coalesce(sum(points), 0) from scores where player = p_player group by player; $$; ``` Any `create function` works, including triggers on your tables. The SQL editor applies it as a versioned change like any other schema change. ## Calling it ```ts const { data, error } = await fenaura.rpc('add_score', { p_player: me.data.user.endUserId, p_points: 5, }); if (error) throw error; // data is the function's result rows: // [{ player: "...", total: 15 }] ``` The response is the standard query envelope: `data` holds the rows the function returned (an empty array for functions that return nothing), `count` when you asked for one, and `request_id` either way. Argument names must match the function's parameter names exactly, and they are passed as named parameters, so order does not matter. A function with no arguments takes none: ```ts const { data } = await fenaura.rpc('active_players'); ``` ## What it runs as The function executes with the calling user's identity. Row level security applies exactly as it does for reads and writes through the builder, so a function that touches other users' rows is stopped by the same policies that stop the user directly. See [Security and RLS](/database/security). This is also why a function is not a back door: writing `security definer` does not lift the caller into the owner's shoes. ## What the platform refuses | Code | Meaning | |---|---| | `UNKNOWN_FUNCTION` | No function with that name in the project's schema | | `INVALID_FUNCTION` | The name exists but is a procedure or an aggregate, not a plain function | | `DEFINER_FUNCTION` | The function is marked `SECURITY DEFINER`; rewrite it as a normal function | | `RPC_FAILED` | The function itself raised an error; check your SQL | `SECURITY DEFINER` deserves a sentence of why: a definer function runs as its owner instead of its caller, which would let any signed-in user borrow the table owner's rights. Fenaura refuses them outright rather than audit each one. ## When to use a function instead of a Fleet A Postgres function is for logic that lives next to the data and runs in one round trip. A Fleet is for logic that needs the network: calling an external API, sending an email, signing a token. If your step is "update these rows atomically", a function wins; if it is "then call Stripe", a Fleet does. --- # Promotion, worked example URL: https://docs.fenaura.dev/database/promotion Section: Database # Promotion, worked example Promotion moves a schema change from development to production. This page walks one change all the way through, including the part that usually goes wrong: removing a column. The rule that governs everything below is short, and worth reading twice. > **Promotion copies structure, never data.** It compares the shape of the two > databases and generates the DDL to make production match development. It does > not copy rows, and it never overwrites a production row with a development > one. Your customer data in production stays exactly where it is. Open it at [Database › Promote](/app/projects/:projectId/database/promote). The [Migrations (Sync)](/app/projects/:projectId/database?sub=migrations) tab shows the same comparison and the history of applied promotions and rebases. ### Reading the sync badge at the upper right The small status badge on the database pages reports the structural comparison before you open a promotion: | Badge | Meaning | What to do | |---|---|---| | Green, `In sync` (`#22c55e`) | Both structures match | Nothing. Deploy your code when ready. | | Gold (`#f59e0b`), `Push to Prod` / `Pull from Prod`, or `Send to Dev` / `Pull from Dev` | One side is ahead | Open [Database › Promote](/app/projects/:projectId/database/promote) and move the structure in the labelled direction. | | Red, `Reconcile schemas` (`#ff3b30`) | Both sides changed, or the diff is destructive | Open the promotion page, read every warning, resolve the conflict before applying. Destructive changes need explicit confirmation. | | Grey, `No dev sandbox` | No development database yet | Create one from [Environments](/environments). | The label follows the environment switch in the header. When Development structure is ahead, Production reads `Pull from Dev` and Development reads `Push to Prod`. When Production alone is ahead, Production reads `Send to Dev` and Development reads `Pull from Prod`. Both cases use the same promotion page, only the direction changes. ## What promotion is not It is not a database copy, a dump and restore, or a sync. Development and production hold different data on purpose. If promotion copied data, your carefully tested development rows would land in production and your real users would be replaced by test accounts. It also does not run automatically. Development schema changes are decoupled from production by design, for three reasons: - a development `DROP COLUMN` must never delete production customer data - a migration against a busy production table takes an `ACCESS EXCLUSIVE` lock, which is an outage - auto-syncing mid-development would deploy half-finished shapes So you iterate freely in development, then promote when the shape is ready. ## The example Start with a fresh project. It has a `users` table in both environments: ```sql id uuid primary key email citext unique name text created_at timestamptz ``` ### 1. Create the development database If the project has no development database yet, create one from the [Environments](/environments) page. This gives you a development sandbox to experiment in, without touching production. ### 2. Make the change in development only Open the [SQL editor](/database/sql-editor), make sure the environment switch reads **Development**, and add a column: ```sql ALTER TABLE users ADD COLUMN last_seen timestamptz; ``` That change now exists in development and nowhere else. Production still has the old shape: no `last_seen`. Nothing has broken for your users, because nothing has changed for them. ### 3. Promote Open the Environments page and start a promotion. Fenaura compares the two structures and shows you the diff **before** applying anything, along with any safety warnings. For this change the diff is one statement: ```sql ALTER TABLE users ADD COLUMN last_seen timestamptz; ``` Apply it inside a single transaction (`lock_timeout = '5s'`, `statement_timeout = '30s'`). Production now has the column. Its existing rows get `NULL` for `last_seen`, which is what a new nullable column means. No row is copied, deleted or rewritten, and every other value in every production row is untouched. If a lock cannot be acquired within 5 seconds, the transaction rolls back cleanly so production traffic is never stalled. If production's structure already matches development, promotion says so: *"Production database structure is already in sync with Development."* Running it twice is not harmful. ### 4. Promote a second change Add another column in development: ```sql ALTER TABLE users ADD COLUMN plan text NOT NULL DEFAULT 'free'; ``` Promote again. Because the statement carries a default, existing production rows get `'free'` in the same operation. Again: no data copied, only a shape change that happens to fill in a value it must fill in. ### 5. Remove a column: the dangerous case Back in development, drop it: ```sql ALTER TABLE users DROP COLUMN plan; ``` Promote. This is where promotion stops being a formality, because applying the drop to production would **destroy every production user's `plan` value**. The schema alone cannot tell you that the data is worth keeping. So promotion treats this as destructive and refuses to proceed passively: - It requires **project admin** rights, not just write access. - It returns `CONFIRMATION_REQUIRED` with the list of warnings, and applies nothing until you present a single-use confirmation token. Read the warnings. The token is not a formality; it is the one moment where a human decides that deleting that column is intended. If it is not, remove the `DROP COLUMN` from development instead and promote the corrected shape. ### 6. The safe way to remove a column If you genuinely want the column gone, do it in stages rather than one destructive leap: 1. **Stop writing to it.** Deploy code that no longer inserts or updates `plan`. 2. **Wait.** Give every in-flight request and cached deploy a chance to age out. 3. **Only then** drop it in development and promote with the confirmation token. Doing it in that order means that at every step, the code that runs against production is compatible with the schema production actually has. ## Why the diff matters The statement list is generated from a real comparison of the two structures, not from a log of what you typed. That is why promotion can tell you the databases are already in sync, and why it can list exactly the destructive statements before running them. It also means hand-editing production outside the editor shows up in the next diff as drift you can see. ## Rules of thumb **Add, do not rename.** A rename is a drop plus an add as far as the database is concerned. Add the new column, write to both, then drop the old one in a later promotion. **Never promote to fix a data problem.** Promotion changes shape. If production rows have wrong values, that is a data fix in the SQL editor, with the environment switch on Production, and you should look at the rows first. **Destructive means read the list.** `DROP COLUMN`, `DROP TABLE` and friends arrive with warnings and need a token. If you find yourself approving them quickly, that is the habit to break. ## Next - [What Row Level Security protects](/database/rls): why a promoted table is never left without policies. - [SQL editor](/database/sql-editor): where you ran the statements above. - [Environments](/environments): the shared quota both environments draw from. --- # Realtime URL: https://docs.fenaura.dev/realtime Section: Realtime # Realtime Realtime updates your app the moment something happens, with no page reloads and no timer loops asking your server "anything new yet?". With one Realtime connection, your app can do five things: 1. **Private 1-on-1 DMs**: direct encrypted chat between two users with typing indicators, read receipts, and presence. 2. **Private Group Chats**: create a group with specific users, manage members, and encrypt every message by default. 3. **Watch database tables**: update the screen the instant a row is added, edited, or deleted. 4. **Send room messages (Broadcast)**: pass fast messages between connected users without touching Postgres. 5. **Show who is online (Presence)**: keep a live list of everyone active in a room. If you already set up `fenaura-sdk` from [Quickstart](/quickstart), everything is ready to go. ## Step 1: Turn on a table (only for database updates) If you only want **1-on-1 DMs**, **Group chats**, **Broadcast**, or **Presence**, skip straight to Step 2. To stream live row changes from a Postgres table: 1. Open your project in the dashboard and go to **Realtime** (on desktop click **Realtime** in the sidebar; on mobile tap **Menu** then **Realtime**). 2. Find the table under **Tables** and turn the switch **ON**. Tip: on **Database › Tables** (especially handy on mobile), each table card also has a compact **RT off** / **RT** button you can tap directly to switch Realtime **ON**. Make sure the environment switcher in the header (**Production** or **Development**) matches the environment your app calls. Turning on a table in Development only streams Development rows. ## Step 2: Use your existing Fenaura client (`fenaura.ts`) Import `fenaura` from `fenaura.ts` (if you have not created it yet, go back to [Quickstart Step 4](/quickstart#4-call-createclient) to create `fenaura.ts`): ```ts // fenaura.ts import { createClient } from 'fenaura-sdk'; export const fenaura = createClient('/fenaura', 'your-project-id'); ``` For websites using `fenaura-sdk`, Fenaura reuses the user's browser session through your `/fenaura` proxy, so WebSocket connections authenticate automatically with no extra keys or manual tokens. > **Building a mobile app, desktop app, CLI, or not using the browser SDK?** > Jump to [Connect without the browser SDK (mobile, desktop, and other apps)](#connect-without-the-browser-sdk-mobile-desktop-and-other-apps) below. ## Build a 1-on-1 encrypted DM chat in 10 lines `fenaura.realtime.dm(friendUserId)` creates a private room between the signed-in user and `friendUserId`. End-to-end encryption is **ON by default**, and Fenaura blocks anyone else from joining on the server: ```ts import { fenaura } from './fenaura'; const chat = fenaura.realtime.dm(friendUserId); // Listen for decrypted messages (payload is your exact string or JSON object) chat.onMessage(({ payload, text, sender_id, ts }) => { console.log(sender_id, 'wrote:', payload); }); // Know who is typing right now (clears automatically after 3.5s or when they send) const stopTypingWatch = chat.onTypingUsers((typingUserIds) => { setSomeoneTyping(typingUserIds.includes(friendUserId)); }); // Send encrypted messages, typing state, and read receipts await chat.sendTyping(true); await chat.sendMessage('Hey! Are you free for lunch?'); await chat.sendMessage({ text: 'Here is the photo', imageUrl: 'https://...' }); await chat.sendRead('msg_123'); // Close cleanly when the user navigates away stopTypingWatch(); chat.close(); ``` `fenaura.realtime.dm(peerUserId)` resolves your own signed-in `myUserId` automatically from your active session and pairs it with `peerUserId` (the recipient's user UUID from your app's profiles/users directory), then registers your device key for multi-device E2EE. If you already have both UUIDs in state, you can also call `fenaura.realtime.dm(myUserId, peerUserId)` explicitly to skip the extra lookup; the server still verifies your session matches one of the two IDs. ## Build a private encrypted group chat Create a group with an explicit member list. Fenaura enforces membership on the server so **non-members cannot join, listen, broadcast, or see presence**, and every message is encrypted by default for every active member's devices: ```ts import { fenaura } from './fenaura'; // 1. Create a private group (caller becomes 'owner') const { data: group, error } = await fenaura.realtime.createGroup({ name: 'Weekend Trip', members: [aliceId, bobId], }); // 2. Open the encrypted group chat room const room = fenaura.realtime.group(group.id); room.onMessage(({ payload, text, sender_id, ts }) => { console.log(`${sender_id}: ${text}`); }); // Show live typing users ("Alice, Bob are typing...") room.onTypingUsers((userIds) => { setActiveTypers(userIds); }); // Track who is currently online inside this group await room.track({ name: 'Ada', status: 'online' }); room.onPresence(({ online }) => { setOnlineMembers(online); // [{ presenceKey, user_id, name, status }, ...] }); // Send an encrypted message (strings or objects work identically) await room.sendMessage('Hey team, I booked the cabin!'); // Manage members (owner/admin only; removed members are kicked immediately) await room.addMembers([charlieId]); await room.removeMember(bobId); // Or leave the group yourself await room.leave(); ``` ### List groups and listen for new group invites Fetch the signed-in user's groups when your chat sidebar loads, and listen for real-time invites or removals on their personal channel: ```ts // Fetch all groups I belong to const { data: myGroups } = await fenaura.realtime.listGroups(); // Update the sidebar the instant someone adds or removes me const stopInvites = fenaura.realtime.onInvite(({ event, payload }) => { if (event === 'group_invite') { addGroupToSidebar(payload); // { group_id, name, topic, member_ids, added_by } } if (event === 'group_removed') { removeGroupFromSidebar(payload.group_id); } }); ``` ## How Fenaura End-to-End Encryption (E2EE) works Encryption is enabled by default on `dm()` and `group()` with zero configuration: 1. **Zero-knowledge server**: messages are encrypted inside the user's browser/device before leaving WebSocket or HTTP requests. Fenaura never sees plaintext messages or private keys. 2. **Forward-fresh per-message keys (enc:v2)**: every message creates a fresh random 256-bit `AES-GCM` data key (DEK) wrapped with ephemeral + static `ECDH P-256` and `HKDF-SHA256`, with full context AAD (`project_id`, room `topic`, `sender_id`, `key_epoch`). 3. **True multi-device support**: each phone, laptop, or browser tab registers its own device key (without overwriting the others). Every sent message wraps the DEK for every active device of every participant, including your own other devices, so you never get stuck reading `"enc:v2..."` ciphertext strings on another device. 4. **Never exposes raw ciphertext**: `onMessage` only puts clean decrypted values into `payload` and `text`. If decryption ever fails because an older device key is missing on a brand-new login, `decrypted` is `false` and `payload` stays `null` instead of printing garbled strings. ### Saving and loading encrypted Postgres chat history Realtime handles live delivery. When you also save messages in your Postgres `messages` table for scrollback history, use `chat.encrypt()` before inserting and `chat.decryptMany()` after querying: ```ts // Save an encrypted message to Postgres AND broadcast live const { envelope } = await chat.sendMessage('Hello from history!'); await fenaura.from('messages').insert({ room_id: chat.topic, sender_id: myUserId, body: envelope, // stored as opaque 'enc:v2:...' ciphertext in Postgres }); // Load & decrypt history rows cleanly on page reload const { data: rows } = await fenaura .from('messages') .select('*') .eq('room_id', chat.topic) .order('created_at', { ascending: true }); const messages = await chat.decryptMany(rows || [], { bodyField: 'body', senderField: 'sender_id', }); // Each item now has item.body & item.text decrypted, plus item.decrypted: true ``` ### Multi-device key backup & restore (optional) If a user logs in on a brand-new phone or clears browser data and needs to decrypt older history sent to an old device key, let them save and restore a passphrase-locked backup (`PBKDF2-SHA256` 310,000 iterations + `AES-GCM-256` inside the browser; Fenaura never sees the passphrase): ```ts // Save an encrypted key backup await fenaura.crypto.backupKeys(recoveryPassphrase); // On a brand-new device after signing in, restore historical device keys await fenaura.crypto.restoreKeys(recoveryPassphrase); ``` ## Watch live database changes Listen for rows added, updated, or deleted on any table you turned on in Step 1. Users only receive row changes allowed by your table's Postgres Row Level Security (RLS) rules: ```ts import { fenaura } from './fenaura'; const stop = fenaura.realtime.table('messages', { event: '*' }, (change) => { console.log('What happened:', change.eventType); // 'INSERT' | 'UPDATE' | 'DELETE' console.log('New row:', change.new); // null on DELETE console.log('Previous row:', change.old); // { id } on DELETE, null on INSERT/UPDATE }); // Call stop() when the screen or component closes ``` Filter to one event type (`'INSERT'`, `'UPDATE'`, or `'DELETE'`) or `column=eq.value`: ```ts const stop = fenaura.realtime.table( 'orders', { event: 'UPDATE', schema: 'public', filter: 'status=eq.shipped', }, (change) => { showBanner(`Order ${change.new.id} has shipped!`); }, ); ``` ## Broadcast messages and presence in open rooms Broadcast sends lightweight JSON to connected users in a room without saving to Postgres, and Presence tracks who is online right now (clearing them automatically if they close their tab or lose connection): ```ts const room = fenaura.channel('public:room-1', { config: { broadcast: { self: false } }, // set true to also hear your own sends }); room .on('broadcast', { event: 'message' }, ({ payload, sender_id, ts }) => { console.log(`${sender_id} said:`, payload, 'at', ts); }) .on('presence', { event: 'sync' }, ({ online }) => { console.log('Online users:', online); }) .subscribe(async (status) => { if (status === 'SUBSCRIBED') { await room.track({ name: 'Ada', status: 'online' }); await room.send({ type: 'broadcast', event: 'message', payload: { text: 'Hello everyone!' }, }); } }); ``` Use `event: '*'` inside `.on('broadcast', { event: '*' }, cb)` if you want one callback to hear every broadcast event on that channel. ## Channel access control (who can join) Pick the channel prefix matching who is allowed in: | Channel format | Server enforcement | Good for | |---|---|---| | `group:` | Only active members in that group | Encrypted group chats with member management | | `dm::` | Only those two users | Private 1-on-1 encrypted DMs | | `user:` | Only that exact user ID | Personal notifications, group invites, unread badges | | `private:user::` | Only that user ID (allows sub-channels, no token needed) | Multiple user-owned private workspaces or synced drafts | | `private:` | Only users holding a Fleet-signed channel token | Paid tiers, role-gated rooms | | `public:` | Any signed-in user in your project | Public lobbies, open feeds | ### Private invite-only rooms (with Fleets) For custom `private:` topics, mint a signed token inside a private Fleet endpoint (`ctx.user` is already verified by the gateway): ```ts // Inside a Fenaura Fleet endpoint (private route: 401 is handled before your code runs) export default async (req, ctx) => { const topic = 'private:team-alpha'; const { token } = await ctx.realtime.token(topic, { userId: ctx.user.userId, ttlSecs: 3600, }); return ctx.json({ topic, token }); }; ``` Pass that `token` when joining from your client: ```ts const teamRoom = fenaura .channel('private:team-alpha', { token }) .on('broadcast', { event: '*' }, (ev) => console.log(ev)) .subscribe(); ``` ## Send live updates from your backend (Fleets) Any Fleet handler can push an event straight to connected clients using `ctx.realtime.publish`: ```ts await ctx.realtime.publish(`user:${targetUserId}`, 'invoice_paid', { invoiceId: 'inv_123', amount: 2900, }); ``` ## Connection status & cleanup Watch socket state changes or close everything cleanly on sign-out: ```ts const stopStatus = fenaura.realtime.onStatus((status) => { // 'DISCONNECTED' | 'CONNECTING' | 'CONNECTED' console.log('Realtime status:', status); }); // Close all active channels and WebSockets fenaura.realtime.disconnect(); ``` ## Connect without the browser SDK (mobile, desktop, and other apps) Mobile apps (Kotlin, Swift, Flutter, React Native), desktop PC apps, CLIs, and custom backends do not have your website's `/fenaura` cookie proxy. Sign the user in with [`browser_flow: false`](/sdk/fetch#sign-in-server-mobile-cli-browserflow-false) and store the returned session token securely on the device (Keychain, Android Keystore, SecureStore, or OS credential storage). ### Option A: Using `fenaura-sdk` in React Native, Electron, or Node Point `createClient` directly at `https://api.fenaura.dev` and call `fenaura.setSession(sessionToken)`: ```ts // fenaura.ts (non-browser JS/TS client) import { createClient } from 'fenaura-sdk'; export const fenaura = createClient('https://api.fenaura.dev', 'your-project-id'); // After signing in with browser_flow: false, pass the stored session token: fenaura.setSession(sessionToken); // Encrypted DMs, encrypted groups, typing indicators, presence, and table watchers all work identically: const chat = fenaura.realtime.dm(friendUserId); chat.onMessage(({ payload }) => console.log('DM:', payload)); await chat.sendMessage('Hey from mobile!'); ``` > Note for React Native / Expo: pass a persistent storage adapter (`{ cryptoStorage: AsyncStorageOrSecureStore }`) into `createClient(..., { cryptoStorage })` if your runtime does not provide browser `localStorage` or `IndexedDB`, so device E2EE keys survive app restarts. ### Option B: Direct REST + WebSocket (Kotlin, Swift, Flutter, Python, Go) Use your stored `sessionToken` (from `browser_flow: false`) with `Authorization: Bearer `: - **Groups REST**: `POST /realtime/groups`, `GET /realtime/groups`, `GET /realtime/groups/`, `POST|DELETE /realtime/groups//members` - **E2EE device keys REST**: `POST /auth/dp/e2ee/key`, `GET /auth/dp/e2ee/keys?ids=,` - **WebSocket**: either pass `Authorization: Bearer ` on upgrade to `wss://api.fenaura.dev/realtime/websocket?project=`, or mint a 60s single-use `?ticket=` first when your client cannot set upgrade headers (browsers/WebSockets without headers): ```ts const API_URL = 'https://api.fenaura.dev'; const WS_URL = 'wss://api.fenaura.dev'; const PROJECT_ID = '9f2c4e1a-6b3d-4c8e-a7f5-2d1b0e9c8a74'; // from Project Overview // 1. Exchange your session token for a 60s single-use WS ticket const { data } = await fetch(`${API_URL}/realtime/ticket?project=${PROJECT_ID}`, { method: 'POST', headers: { Authorization: `Bearer ${sessionToken}` }, }).then((r) => r.json()); // 2. Connect, join a channel or table stream, and keep a 20s ping alive const ws = new WebSocket(`${WS_URL}/realtime/websocket?project=${PROJECT_ID}&ticket=${data.ticket}`); ws.onopen = () => { ws.send(JSON.stringify({ type: 'join', topic: `group:${groupId}` })); const ping = setInterval(() => ws.readyState === 1 && ws.send('{"type":"ping"}'), 20_000); ws.onclose = () => clearInterval(ping); }; ws.onmessage = ({ data: raw }) => { const frame = JSON.parse(raw); if (frame.type === 'system' && frame.event === 'joined') { ws.send(JSON.stringify({ type: 'broadcast', topic: frame.topic, event: 'message', payload: { text: 'Hello' } })); } if (frame.type === 'broadcast' || frame.type === 'postgres_changes') { console.log(frame); } }; ``` Outgoing WebSocket frames supported by the server: | `type` | Required fields | Optional fields | What it does | |---|---|---|---| | `join` | `topic` | `ref`, `config` (`broadcast.self`, `presence.key`, `token`, `postgres_changes`) | Join a DM, group, or room and/or subscribe to live table changes | | `leave` | `topic` | `ref` | Leave a channel and stop its table/presence subscriptions | | `broadcast` | `topic`, `event`, `payload` | | Send a JSON event to everyone else in the joined room | | `presence_track` | `topic`, `state` | | Publish your online state to the joined room | | `presence_untrack` | `topic` | | Remove your presence state without leaving the room | | `ping` | | `ref` | Replies with `{ "type": "pong", "ref", "ts" }` | ## Good to know | Item | Limit | Notes | |---|---|---| | Max message size | **256 KiB** | Larger broadcast or table payloads are rejected/dropped | | Group members | **100** | Maximum members per managed group chat | | E2EE devices per user | **8** | Oldest inactive device keys auto-prune past 8 per account | | Channels per socket | **64** | Call `unsubscribe()` (or `close()`) when leaving a view | | Ticket lifetime | **60 seconds** | Single-use auth ticket from `POST /realtime/ticket` | | Environments | **Separate** | `development` and `production` keys, groups, sessions, and traffic never mix | To watch live connections and test broadcasts without writing code first, open **Realtime › Live** in your dashboard. For a single-page index of every direct HTTP and WebSocket endpoint (`https://api.fenaura.dev` and `wss://api.fenaura.dev`), see the [Direct API URLs Reference](/platform/direct-urls). --- # Edge functions URL: https://docs.fenaura.dev/edge Section: Edge functions # Edge functions An edge function is your backend. It runs in a V8 isolate, the browser's JavaScript engine without the browser, which starts in milliseconds and does not keep state between requests. One function per environment. A deployment replaces the whole thing, so a route you delete is gone. ## Private by default This is the property that shapes how you write handlers. Every route is checked for a signed-in end user **before your code runs**. ```ts // main.ts // Reaching this line means someone signed in. return ctx.json({ hello: ctx.user.identifier }); ``` *(You can also write `export default async (req, ctx) => { ... }` if you want, but the Fleets IDE wraps plain `main.ts` code for you automatically.)* An unauthenticated request to a private route is rejected upstream. Your handler never sees it. There is no `if (!user) return 401` to forget, and no route left open by omission. To serve anonymous traffic you declare the route public. That is one deliberate act, visible in one place, rather than a scattered convention. See [Public routes](/edge/public-routes) for what that really changes. ## Deploying Write the function in the dashboard's Fleet editor, or let Veilo write it, and deploy. The code is bundled at deploy time, so imports are resolved then. You can run `npm install ` in the Fleet IDE terminal, or ask Veilo to install it, and the package is added to the project's database-backed virtual `node_modules` and bundled into the deployment. Uninstalled edge-compatible imports can resolve from `esm.sh` at build time. Nothing is installed inside the running isolate. See [Using npm packages](/fleets/ide#using-npm-packages). ## Calling it - **From a browser (same-origin proxy so session cookies follow):** - Production: `/fenaura/fleet/{token}/your/path` (with `credentials: 'include'`) - Development: `/fenaura/fleet/dev-{token}/your/path` (with `credentials: 'include'` for a signed-in, approved development user, never put `X-Fenaura-Dev-Key` in frontend code) `/fenaura/fleet/*` proxies to `https://edge.fenaura.dev/*` behind the scenes (just like `/fenaura/*` proxies to `https://api.fenaura.dev/*`), keeping cookies on your app's own domain. - **From non-browser environments (server, mobile, CLI, webhooks):** - Production: `https://edge.fenaura.dev/{token}/your/path` - Development: `https://edge.fenaura.dev/dev-{token}/your/path` (with `X-Fenaura-Dev-Key` or `Authorization: Bearer ` from signing in with [`browser_flow: false`](/sdk/fetch#sign-in-server-mobile-cli-browserflow-false)) `{token}` is the project's 7-character edge token, shown on the project's overview page and in the Fleets IDE. Append the route path directly. There is no `/default` segment. Never use `/fenaura/edge/...` (that routes to `api.fenaura.dev`). ## Responses: status codes, headers, cookies, and redirects ### Status codes Pass the HTTP status code as the second argument to `ctx.json`, `ctx.text`, `ctx.html`, or in `new Response(body, { status })`: ```ts return ctx.json({ created: true }, 201); // or: return new Response(JSON.stringify({ error: 'Invalid input' }), { status: 400, headers: { 'content-type': 'application/json' }, }); ``` Note: `c.status(...)` in Hono-style handlers is a no-op in the runtime shim. Always pass the status code directly to `c.json(data, status)`, `c.text(text, status)`, `c.html(html, status)`, or `new Response(...)`. ### Response headers Set custom response headers with `c.header(name, value)` or `new Response(body, { status, headers })`: ```ts app.get('/hello', (c) => { c.header('x-custom-header', 'fenaura'); return c.json({ ok: true }, 200); }); ``` Gateway rules on response headers: - `Content-Type` defaults to `application/json` if you do not set one. - `Cache-Control` is always set to `no-store` by the gateway so stale deployments are never cached. - `Access-Control-Allow-Origin` echoes your allowlisted request `Origin` (never `*`), unless you set an allowlisted `Access-Control-Allow-Origin` header yourself. - Hop-by-hop and platform headers (`connection`, `content-length`, `date`, `host`, `keep-alive`, `proxy-authenticate`, `proxy-authorization`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `x-fenaura-request-id`, `x-fenaura-execution-time-ms`) are stripped. ### Cookies (`Set-Cookie`) and redirects (`Location`, `Refresh`) - **Cookies (`Set-Cookie`) are stripped.** Edge functions cannot set `Set-Cookie` headers on responses. End-user session cookies are managed exclusively by Fenaura Auth endpoints (`/auth/...` via your `/fenaura/*` proxy), or via `Authorization: Bearer ` headers. - **Redirects (`Location`, `Refresh`) are stripped.** Edge functions cannot return HTTP `Location` or `Refresh` redirect headers from `edge.fenaura.dev`. Return JSON (for example `{ redirectTo: '/next' }`) and let your frontend navigate. ## What an edge function is not - **Not a container.** A Fleet handler runs in a V8 isolate: no shell, no `fs` API and no disk that survives a request. npm packages are installed into the project at build time and bundled into the deployment, see [Using npm packages](/fleets/ide#using-npm-packages). Persistent files belong in `ctx.storage`. - **Not long-running.** A request has a time limit; work that takes minutes belongs in a queue elsewhere. - **Not stateful.** Each request may land on a fresh isolate. Use the database or `ctx.redis` for anything that must persist. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Your first function](/edge/first-function): build and deploy one. - [The context object](/edge/context): every field on `ctx`. - [Rate limits](/edge/rate-limits): the real numbers. - [Errors](/edge/errors): the codes and what to do about them. --- # Your first function URL: https://docs.fenaura.dev/edge/first-function Section: Edge functions # Your first function An edge function is server code you deploy to Fenaura. All of your backend code starts in `main.ts` inside the dashboard's **Edge Functions** editor. When a request hits your function's URL, Fenaura checks who is calling, connects your project database, and runs `main.ts` with both ready to use. This page builds up in six small steps. Each one ends with something you can run and see. ## Step 1: return something from `main.ts` Open your project's **Edge Functions** editor. You don't need to wrap your code in an `export default` function; the Fleets IDE wraps `main.ts` for you automatically. Just write: ```ts // main.ts return ctx.json({ hello: 'world' }); ``` `req` and `ctx` are already available in `main.ts` (if you prefer, you can also write `export default async (req: any, ctx: any) => { ... }` explicitly). You can call `ctx.json(data, status)` or return a plain object like `{ hello: 'world' }`. To put the code live, open the **⋯** menu at the top right of the Fleets IDE header (on mobile it is the same **⋯** button in the header), scroll to **Advanced · Deployment & Run**, and choose **Deploy to Development**. Each deploy replaces the whole development function. ## Step 2: call it Every project has its **Fleet URL** on **Project Overview**, with a dropdown that defaults to the session-gated browser proxy path (**Fleet (Browser)**, `/fenaura/fleet/...`) and switches to the **Full Fleet URL** (`https://edge.fenaura.dev/...`) for servers, CLIs, and non-browser clients. To test quickly from your terminal against development, call your project's development fleet URL with your dev key: ```bash # Copied from Project Overview -> Fleet URL (Full Fleet URL in Development) FLEET_URL="https://edge.fenaura.dev/dev-k7m9x2p" curl "$FLEET_URL" \ -H "X-Fenaura-Dev-Key: " ``` You should see: ```json { "hello": "world" } ``` Without `X-Fenaura-Dev-Key` (or a verified dev session), Fenaura rejects the request with `401 DEV_ACCESS_DENIED` before your code runs. The dev key keeps your development deployment private to you, and you can rotate it any time from **Project Overview**. ## Step 3: read the request `req` gives you `req.method`, `req.path`, `req.query`, `req.headers`, `req.url`, and `req.body`. Read a query parameter and echo it back: ```ts // main.ts const url = new URL(req.url); const name = url.searchParams.get('name') || 'stranger'; return ctx.json({ hello: name }); ``` Deploy to dev and call it with `?name=ada`. For a `POST` request, `req.body` is already parsed from JSON if the body was valid JSON (or a string if it wasn't, or `null` if the body was empty). Always validate it before using it: ```ts // main.ts const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); if (typeof body?.title !== 'string' || !body.title.trim()) { return ctx.json({ error: 'A title is required' }, 400); } return ctx.json({ title: body.title.trim() }); ``` `ctx.user` is trustworthy because the platform produced it. `req.body` is whatever the caller chose to send, so always check it first. ## Step 4: know who is calling - **From a browser:** Call `/fenaura/fleet/{token}/...` in production or `/fenaura/fleet/dev-{token}/...` in development with `credentials: 'include'` (never put `X-Fenaura-Dev-Key` in frontend code). Your `/fenaura/fleet` proxy forwards to `https://edge.fenaura.dev` behind the scenes so your first-party session cookie follows; calling `edge.fenaura.dev` directly from a browser carries no cookie and fails with `401`. - **From non-browser environments (server, mobile, CLI, webhooks):** Call `https://edge.fenaura.dev/{token}/...` (or `https://edge.fenaura.dev/dev-{token}/...` in dev) directly with `Authorization: Bearer ` (obtained by signing in with [`browser_flow: false`](/sdk/fetch#sign-in-server-mobile-cli-browserflow-false)) or `X-Fenaura-Dev-Key` in development. Storing that end-user token securely on mobile (Keychain / SecureStore) or desktop/PC is your responsibility, then attach it in the `Authorization` header on every call. Because Fenaura sessions are cookies, pass `credentials: 'include'` on every plain browser `fetch` (`fenaura-sdk` sets it automatically): ```ts await fetch(`${FLEET_URL}/api/notes`, { credentials: 'include' }); ``` When the request is authenticated, `ctx.user` is populated before `main.ts` runs: ```ts // main.ts return ctx.json({ userId: ctx.user.userId, identifier: ctx.user.identifier, }); ``` ## Step 5: use the database `ctx.db.query(sql, params)` runs parameterized SQL (`$1`, `$2`, ...) against your project's database and returns an array of row objects (see [Drizzle in the edge](/database/drizzle) for database queries). Read the signed-in user's rows: ```ts // main.ts const notes = await ctx.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [ctx.user.userId], ); return ctx.json({ notes }); ``` And to insert a row: ```ts // main.ts const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); const title = typeof body?.title === 'string' ? body.title.trim() : ''; if (!title) { return ctx.json({ error: 'A title is required' }, 400); } const rows = await ctx.db.query( 'insert into notes (title, owner) values ($1, $2) returning *', [title, ctx.user.userId], ); return ctx.json({ note: rows[0] }, 201); ``` Always filter by `ctx.user.userId` in your `where` clause so one user never reads another user's rows. ## Step 6: run it from your app, then promote 1. Start your frontend app and sign in as an end user in development. 2. Call your deployed dev function from the page via `/fenaura/fleet` (so your browser session cookie rides along): ```ts // Copied from Project Overview -> Fleet URL (Fleet (Browser) in Development) const FLEET_URL = '/fenaura/fleet/dev-k7m9x2p'; const res = await fetch(`${FLEET_URL}/api/notes`, { credentials: 'include', }); const data = await res.json(); ``` *(Never put `X-Fenaura-Dev-Key` in frontend `VITE_*` variables; signed-in, approved development users authenticate via their browser session cookie with `credentials: 'include'`. Use `X-Fenaura-Dev-Key` only for `curl` or server-side scripts.)* 3. Load the page; you will see the rows for that user. When everything works in development, deploy the same code to production. Production has its own separate database, so your dev test rows stay in dev. In your frontend, switch from `dev-k7m9x2p` to `k7m9x2p` in production builds: ```ts const FLEET_URL = import.meta.env.DEV ? '/fenaura/fleet/dev-k7m9x2p' : '/fenaura/fleet/k7m9x2p'; await fetch(`${FLEET_URL}/api/notes`, { credentials: 'include' }); ``` ## Common gotchas - **Appending `/default` to the URL** returns `404` (there is no `/default` segment). - **Calling a development URL without `X-Fenaura-Dev-Key` (or a dev session)** returns `401` before your code runs. - **Calling `?env=test` with a production session** returns `401 SESSION_ENVIRONMENT_MISMATCH`. - **Forgetting `where owner = $1`** returns every user's rows. - **Forgetting `await` on `ctx.db.query(...)`** returns the response before the query finishes. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Routing](/edge/routing): add multiple routes and controllers with Hono or `req.path`. - [The context object](/edge/context): every field on `ctx`. - [Public routes](/edge/public-routes): serving unsigned traffic deliberately. - [Errors](/edge/errors): codes you will meet. --- # The context object URL: https://docs.fenaura.dev/edge/context Section: Edge functions # The context object Every handler receives `(req, ctx)`. `req` has the request fields (`method`, `path`, `query`, `headers`, `body`, `url`), and `ctx` is everything the platform gives you. ```ts // main.ts export default async (req: any, ctx: any) => { return ctx.json({ env: ctx.environment, requestId: ctx.requestId, user: ctx.user?.userId ?? null, }); }; ``` ## Fields ### `ctx.environment` `'test'` or `'production'`. Use it to vary behaviour when you have to, and to refuse to accept a test-only shortcut in production. ```ts if (ctx.environment === 'production' && body.seedDemo) { return ctx.json({ error: 'Not allowed in production' }, 400); } ``` ### `ctx.requestId` A unique id for this request. Return it in error responses and log it, it is the one value that lets you find the exact request later. ```ts return ctx.json({ error: 'failed', requestId: ctx.requestId }, 500); ``` ### `ctx.project` ```ts ctx.project.id // string ctx.project.slug // string ``` Rarely needed, since the function only ever runs for one project. Useful in a log line or a webhook payload. ### `ctx.user` The signed-in end user, or `null` on a public route. ```ts ctx.user.userId // the end user's id ctx.user.identifier // the scoped identity string (email + project) ``` `null` only happens on a route you declared public. On a private route, an unauthenticated request never reaches your handler. ### `ctx.env` The environment variables for this environment, as strings. ```ts const stripeKey = ctx.env.STRIPE_SECRET_KEY; ``` Development and production variables are separate. A key set in development is not set in production, check for `undefined` or you will discover the gap in production. ### `ctx.db` Runs parameterized SQL (`$1`, `$2`, ...) against this project's Postgres database and returns an array of row objects: ```ts const rows = await ctx.db.query( 'select count(*) from notes where owner = $1', [ctx.user.userId], ); ``` Values are always bound by Postgres, never string-interpolated. Never build SQL by concatenating user input. ### `ctx.json(data, status = 200)` Returns a JSON `Response` with `content-type: application/json`. Returning a plain object like `{ ok: true }` also sends JSON with status `200`. ### `ctx.redis` A key-value store for short-lived shared state, counters, rate limits of your own, caches. ```ts const count = await ctx.redis.incr(`views:${id}`); await ctx.redis.expire(`views:${id}`, 3600); ``` Entries take a TTL and count against the project's Redis quota, so they cannot grow without bound. Development and production have separate Redis databases; a key written in one is not visible in the other. ### `ctx.log` Structured logger (`debug`, `info`, `warn`, `error`, and `ctx.log.child(bindings)`) streamed live to the IDE terminal and Dashboard Logs with automatic secret redaction. Always call `ctx.log` directly across plain handlers and Hono routes (never `ctx.env.log`, because `ctx.env` holds your environment variables only): ```ts ctx.log.info('payment.created', { id: rows[0].id, userId: ctx.user.userId }); ``` ## What is not on ctx `ctx.environment` is `'test'` for a Development deployment and `'production'` for a Production deployment. The handler code is the same in both: Development uses a separate database, Redis instance and set of environment variables, so you can stub external calls there and use real keys only in Production. Inside the isolate there is no `fs`, no shell and no `process.env` (use `ctx.env`). Relying on `process` at all will fail, a Fleet is not Node. That is about the running handler, not your project: you can install npm packages in the Fleet IDE terminal and they are bundled at deploy time, and persistent files belong in `ctx.storage` or your database. Also note that `c.env.auth` is never injected (`ctx.env` holds your configured environment variables only, and in Hono `c.env` receives the `ctx` bindings object without an `auth` property), and raw `cookie` / `authorization` headers are stripped at the gateway. Never parse `fenaura_eusid` or fallback Bearer tokens in Edge code; read verified identity solely from `ctx.user` (`userId` and `identifier`). ## Next - [Environments](/edge/environments): test versus production. - [Rate limits](/edge/rate-limits): how much you can send. - [Errors](/edge/errors): the codes and the fixes. --- # Routing URL: https://docs.fenaura.dev/edge/routing Section: Edge functions # Routing Fenaura runs `main.ts` for **every** request to your project's fleet URL. It does not pick a file based on the URL, your code in `main.ts` decides what runs and what response goes back. If you return directly from `main.ts`: ```ts // main.ts return ctx.json({ ok: true, path: req.path }); ``` That answers the base URL (`/fenaura/fleet/{token}` from a browser or `https://edge.fenaura.dev/{token}` from non-browser clients, where `req.path` is `'/'`) and every subpath under it. ## 1. Plain JavaScript routing For a few routes, branch on `req.method` and `req.path` right in `main.ts`: Before the code, three things worth understanding, because they answer the questions people ask when they see this pattern for the first time: **Why both `req.method` and `req.path`.** Your Fleet has one base URL, and everything after it arrives inside the `req` object, exactly like the request object your Express or Hono server hands you. A request has two halves: the method (`GET`, `POST`, `PUT`, `DELETE`) and the path (`/notes`). `req.method` says what the caller wants to do; `req.path` says where. You need both, because `GET /notes` (list notes) and `POST /notes` (create a note) share a path but must do different jobs, and without checking `req.path`, every `POST` or `GET` to **any** path on your Fleet URL would fall into whichever block matches the method alone. **The `/api` (or `/anything`) prefix is your choice.** Fenaura does not know or care what your routes are called. After the base URL, the URL is entirely yours: you define the routes in `main.ts` and you call those exact paths. `/api/notes`, `/notes`, `/v1/whatever`, it is your server's URL space, the same as it would be on a server you ran yourself. **The fallthrough `return` is not Fenaura syntax.** `main.ts` runs from top to bottom like any script. Each `if` in turn gets a chance to handle the request; the first one that matches returns a response and the rest never runs. If nothing matches, execution simply reaches the last statement, which answers `404`. That is the ordinary "routes from top to bottom, then a catch-all" structure every Express server uses; there is no Fenaura-specific routing syntax to learn. ```ts // main.ts if (req.path === '/notes' && req.method === 'GET') { const notes = await ctx.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [ctx.user.userId], ); return ctx.json({ notes }); } const match = req.path.match(/^\/notes\/([^/]+)$/); if (match && req.method === 'GET') { const rows = await ctx.db.query( 'select * from notes where id = $1 and owner = $2 limit 1', [match[1], ctx.user.userId], ); if (!rows.length) return ctx.json({ error: 'Not found' }, 404); return ctx.json({ note: rows[0] }); } if (req.path === '/notes' && req.method === 'POST') { const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); const title = typeof body?.title === 'string' ? body.title.trim() : ''; if (!title) return ctx.json({ error: 'A title is required' }, 400); const rows = await ctx.db.query( 'insert into notes (title, owner) values ($1, $2) returning *', [title, ctx.user.userId], ); return ctx.json({ note: rows[0] }, 201); } return ctx.json({ error: 'Not found', path: req.path }, 404); ``` ## 2. Doing the exact same thing with Hono When your API grows, switch to the built-in `Hono` router. You don't need to write an `export default` bridge, the Fleets IDE wraps `app` automatically, and `ctx` is available inside every handler on `c.env`: ```ts // main.ts import { Hono } from 'hono'; const app = new Hono(); app.get('/notes', async (c) => { const notes = await c.env.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [c.env.user.userId], ); return c.json({ notes }); }); app.get('/notes/:id', async (c) => { const rows = await c.env.db.query( 'select * from notes where id = $1 and owner = $2 limit 1', [c.req.param('id'), c.env.user.userId], ); if (!rows.length) return c.json({ error: 'Not found' }, 404); return c.json({ note: rows[0] }); }); app.post('/notes', async (c) => { const body = await c.req.json().catch(() => ({})); const title = typeof body?.title === 'string' ? body.title.trim() : ''; if (!title) return c.json({ error: 'A title is required' }, 400); const rows = await c.env.db.query( 'insert into notes (title, owner) values ($1, $2) returning *', [title, c.env.user.userId], ); return c.json({ note: rows[0] }, 201); }); ``` `Hono` is provided by the runtime at zero bundle cost (the bundler strips `import { Hono } from 'hono'`). ## 3. Folders, subfolders, and controllers (just like Express) In the Fleets IDE file tree, you can create folders and subfolders (`routes/`, `controllers/`, `lib/`, `routes/v1/`, etc.) and organize your codebase the exact same way you structure an Express server. `main.ts` is your entry file (just like `index.ts` or `server.ts` in Express): ```text main.ts entry file: creates app and mounts routes routes/ notes.ts note routes users.ts user routes controllers/ notes.controller.ts database & validation logic lib/ validate.ts shared helpers ``` ```ts // routes/notes.ts import { Hono } from 'hono'; export const notes = new Hono(); notes.get('/', async (c) => { const rows = await c.env.db.query( 'select * from notes where owner = $1 order by created_at desc limit 20', [c.env.user.userId], ); return c.json({ notes: rows }); }); ``` ```ts // routes/users.ts import { Hono } from 'hono'; export const users = new Hono(); users.get('/me', (c) => c.json({ user: c.env.user })); ``` ```ts // main.ts import { Hono } from 'hono'; import { notes } from './routes/notes'; import { users } from './routes/users'; const app = new Hono(); app.route('/api/notes', notes); app.route('/api/users', users); ``` Relative imports are bundled at deploy time into a single deployment. ## 4. npm packages You can import standard npm packages (for example `import { z } from 'zod'`) in your files. Run `npm install ` in the Fleet IDE terminal, or ask Veilo, to add a package to the project's database-backed virtual `node_modules`; the bundler resolves installed packages first and falls back to `esm.sh` for uninstalled imports at deploy time. Keep in mind the isolate has no Node `fs`/`process` APIs, so choose browser/edge-compatible packages. ## Full Fleets reference For the complete reference on `ctx`, request/response headers, status codes, cookies, params, storage, Redis, email, and npm packages, see the **Fleets** section: - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Fleets overview](/fleets) - [Fleets routing](/fleets/routing) - [The full `ctx`, request & response reference](/fleets/context) - [Drizzle in the edge](/database/drizzle) --- # Environments URL: https://docs.fenaura.dev/edge/environments Section: Edge functions # Environments Every project has two environments running the same kind of code with completely separate state. ## Same code, different deployment The Development/Production switch in the project header does not rewrite your source code. It points the dashboard and your Fleet deployments at a different set of resources: a different Postgres database, a different Redis database, separate storage buckets, separate Platform secrets and environment variables, and a separate set of end users. The Fleet editor, the files and the code are the same. You write once and deploy twice, once to the `dev-` URL and once to the production URL. Your laptop is just another place to run that same code against Development resources, it is not a separate kind of backend. Inside a running Fleet handler you can ask which environment it is: ```ts export default async (req: Request, ctx: any) => { const isDev = ctx.environment === 'test'; // In Development, skip the external call and use a harmless dummy value. // In Production, use the real integration. const apiKey = isDev ? 'dummy-key' : ctx.env.PAYMENT_API_KEY; if (!isDev && !apiKey) return ctx.json({ error: 'PAYMENT_API_KEY is missing' }, 500); return ctx.json({ env: ctx.environment, apiKey: isDev ? 'dummy' : 'live' }); }; ``` `ctx.environment` is `'test'` in Development and `'production'` in Production. It is injected by the runtime from the deployment target, so it is reliable on both the proxy path and the direct Fleet URL. `ctx.env` is also separate per environment: set the same key in both places with different values, and the handler picks up the value for the environment it is running in. | | Development | Production | |---|---|---| | Fleet URL | `edge.fenaura.dev/dev-{token}` | `edge.fenaura.dev/{token}` | | Access | dev key or the owner's dashboard session | the URL token itself | | Data | separate database | real user data | | Env vars | separate | separate | | Auth users | separate | real end users | | Emails | captured in the sandbox mailbox | delivered for real | Nothing moves between them by default. That is the point: trying something in development cannot touch a real user. ## Calling a Fleet in development vs production - **From a browser (always the `/fenaura/fleet` proxy so cookies follow):** `/fenaura/fleet/{token}/...` (production) or `/fenaura/fleet/dev-{token}/...` (development, with `credentials: 'include'` for a signed-in, approved development user, never put `X-Fenaura-Dev-Key` in frontend JS). - **From non-browser clients (server, mobile, CLI, webhooks):** `https://edge.fenaura.dev/{token}/...` (production) or `https://edge.fenaura.dev/dev-{token}/...` (development). The split is not a convention, it is where the session lives. Fenaura signs end users in with cookies, and those cookies belong to **your** domain (the `/fenaura` proxy put them there), so a browser request sent directly to `edge.fenaura.dev` arrives with no cookie and is refused with `401`. In a browser, always the proxy path, with `credentials: 'include'` on every call (the SDK sets it for you; plain `fetch` needs it spelled out). Outside a browser there is no cookie jar, so the full URL is correct and identity travels in a header instead: `Authorization: Bearer ` (obtained by signing in with [`browser_flow: false`](/sdk/fetch#sign-in-server-mobile-cli-browserflow-false); mobile, desktop/PC, and backend apps store that token in their own secure storage and attach it on each call), or `X-Fenaura-Dev-Key` for development URLs. ## Deploying Deploy to development, check it with real requests, then promote the same code to production. Promotion copies code, not data. ## Environment variables Set each variable in both environments. A key present in development is `undefined` in production, and the failure appears at the first request that needs it: ```ts const secret = ctx.env.STRIPE_SECRET_KEY; if (!secret) { return ctx.json( { error: 'STRIPE_SECRET_KEY is not set in this environment', code: 'MISSING_ENV' }, 500, ); } ``` Check for the variable and say so in the error. Finding a missing variable from a generic 500 costs twenty minutes; naming it costs one line. ## Calling a development deployment A development URL needs proof that you are allowed to use it: ```bash FLEET_URL="https://edge.fenaura.dev/dev-k7m9x2p" curl "$FLEET_URL/api/notes" \ -H "X-Fenaura-Dev-Key: " \ -H "Authorization: Bearer " ``` The dev key requirement is why a development URL is safe to have in a frontend bundle: knowing the URL is not enough. ## Common mistakes | Mistake | What happens | |---|---| | Setting a variable in one environment only | `undefined` at runtime in the other | | Testing against production data | Real users see test rows | | Pointing a preview deploy at production | Test traffic counted against real limits | | Assuming promoted code brings its env vars | Variables are per environment, always | ## A safe pattern Keep the source of truth in code, and keep secrets in variables: ```ts // Reads the same in both environments const baseUrl = ctx.env.PUBLIC_BASE_URL; // Differs per environment, as it should const stripeKey = ctx.env.STRIPE_SECRET_KEY; ``` Data that differs between environments belongs in `ctx.env`. Anything else should not differ at all. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [The context object](/edge/context): `ctx.environment` and `ctx.env`. - [Rate limits](/edge/rate-limits): preview runs have their own limit. --- # Public routes URL: https://docs.fenaura.dev/edge/public-routes Section: Edge functions # Public routes Every route is private by default. Making one public is a deliberate act, and it is the only way to serve a request from someone who is not signed in. ## Declaring a route public Add the route to the function's public list. It is matched by method and path: ``` POST /webhooks/stripe GET /api/health ``` Anything listed there skips the session check. Everything else keeps it. ## What changes Three things, and all three matter: **1. `ctx.user` is `null`.** The platform has no session, so there is no user to populate. Your handler must decide what to do, usually validate a signature or an API key instead. **2. The rate limit is per project.** A private route counts per end user, so one heavy client cannot starve others. A public route has no user to count against, so the entire project shares 1000 requests per 10 seconds. A traffic spike on a public route can throttle your authenticated routes too. **3. You are now responsible for identification.** There is nothing upstream proving who called. If the route acts on behalf of someone, verify something: ```ts // A webhook: verify the signature, not the caller's identity const signature = req.headers.get('stripe-signature'); if (!signature || !verifyStripeSignature(await req.text(), signature, ctx.env.STRIPE_WEBHOOK_SECRET)) { return new Response('Invalid signature', { status: 400 }); } ``` Never trust a body that claims an identity. `{ userId: 'abc' }` from an anonymous caller means nothing. ## Good reasons to go public | Reason | Protection you add | |---|---| | Receiving a provider webhook | Signature verification | | A health check for monitoring | Nothing needed; return no data | | A public landing-page counter | Rate limit through `ctx.redis` | | An OAuth callback landing page | Validate the one-time code | ## Bad reasons to go public - "It is easier to test without signing in." Sign a test user in instead. - "The frontend calls it before login." Call it after login. - "The data is not sensitive." Then it does not need to be an endpoint at all. ## Adding your own limit Public routes get a per-project limit only. Add a per-caller limit where you need one: ```ts const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'; const key = `rl:pub:${ctx.project.id}:${ip}`; const hits = await ctx.redis.incr(key); if (hits === 1) await ctx.redis.expire(key, 60); if (hits > 30) return new Response('Too many requests', { status: 429 }); ``` ## Reviewing what is public The public list is short and lives in one place, read it before every deploy. A route left public after an experiment is the most common way an app leaks data, and it is invisible in the UI because the endpoint still works. Never bypass gateway security by parsing `fenaura_eusid` cookies or `Authorization` headers inside a `{ public: true }` handler (or using custom `session.ts` helpers that accept a raw bearer/cookie value as `{ id: token }`). Private routes are already enforced before your code runs with verified `ctx.user`; public routes intentionally allow anonymous callers where `ctx.user` is `null`. ## Next - [Rate limits](/edge/rate-limits): the full table. - [Security and RLS](/database/security): protecting the rows behind a public route. --- # Rate limits URL: https://docs.fenaura.dev/edge/rate-limits Section: Edge functions # Rate limits Limits are applied before your function runs, by the runtime. Crossing one returns `429` with an error code, and your code does not execute. ## The numbers | Scope | Limit | Window | Error code | |---|---|---|---| | Authenticated requests, per project | 1000 | 10 seconds | `PROJECT_THROTTLED` | | Authenticated requests, per end user | 200 | 10 seconds | `USER_THROTTLED` | | Public routes, per project | 1000 | 10 seconds | `PROJECT_THROTTLED` | | Preview runs, per developer | 60 | 60 seconds | `PREVIEW_THROTTLED` | | Preview runs, per IP | 30 | 60 seconds | `PREVIEW_THROTTLED` | Two of these are worth reading twice. **Per end user is 200 in 10 seconds.** That is a fast, chatty client hammering your own endpoint, usually a polling loop with no backoff. It is not a reasonable interactive rate, and a user who hits it has a bug on your side, not theirs. **Public routes are per project, not per visitor.** A public route has no end user to count against, so the whole project shares one budget of 1000 requests per 10 seconds. If you expect anonymous traffic at volume, cache at the edge or move the endpoint behind a session. ## Your Fleet calls have a second, slower budget Edge requests are metered per 10 seconds. The **database and API calls those requests make** are metered on a *different window*, per 60 seconds: | Scope | Limit | Window | Error code | |---|---|---|---| | Data requests, per project | 1000 | 60 seconds | `PROJECT_THROTTLED` | | Data requests, per end user | 200 | 60 seconds | `USER_THROTTLED` | This matters more than it looks. A handler that makes many queries in one request spends the data budget, not the edge budget. Twenty `findMany` calls in a loop are twenty units in a 60-second window, and the limit surfaces as `429 USER_THROTTLED` on a route that looks lightly used from the outside. The fix is the ordinary one: batch the queries, select only the columns you need, and let the database do the joining rather than looping in JavaScript. ## Public routes have a third guard: per-visitor A public route is reached before any session exists, so it is also metered *per visitor*, not only per project. The runtime uses a hardened cookie to recognise a repeat caller and counts them on a short window: | Scope | Limit | Window | Error code | |---|---|---|---| | Anonymous caller on a public route | 60 | 60 seconds | `PUBLIC_ROUTE_RATE_LIMITED` | | The same caller, burst | 15 | 5 seconds | `PUBLIC_ROUTE_RATE_LIMITED` | Both defaults come from the route's own rate-limit configuration, so you can tune them per route. The limits are the defaults. The caller is identified by a signed cookie (`fenaura_anon_rl`) combined with a hash of their IP and user agent. This is why a public route is safe to expose at moderate volume: one visitor cannot spend the whole project budget, and clearing cookies does not reset the IP-and-device part of the check. When it trips, the response is `429` and carries the usual headers so a client can back off: ``` 429 PUBLIC_ROUTE_RATE_LIMITED retry-after: 60 x-ratelimit-limit: 60 x-ratelimit-remaining: 0 ``` ## What is not a limit There is no per-IP anonymous limiter on routes that require a session, a caller without a session is refused outright with `401 SESSION_MISSING` before any counting happens. Anonymous metering exists only on routes you have declared public. nothing else. If you need per-visitor limits on a public route, implement them yourself with `ctx.redis`: ```ts const key = `rl:${ip}:${ctx.project.id}`; const hits = await ctx.redis.incr(key); if (hits === 1) await ctx.redis.expire(key, 60); if (hits > 30) return new Response('Too many requests', { status: 429 }); ``` Read the caller's address from `req.headers.get('x-forwarded-for')`. It arrives from the platform's proxy; treat it as advisory if your route is public and could be reached through another proxy. ## Handling a 429 correctly Respect the retry hint. A fixed one-second retry on a 10-second window makes the problem worse, because every retry counts. ```ts async function callWithRetry(url: string, init: RequestInit, attempt = 0): Promise { const res = await fetch(url, init); if (res.status !== 429 || attempt >= 3) return res; const retryAfter = Number(res.headers.get('retry-after') || 0); const wait = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000; await new Promise((r) => setTimeout(r, wait)); return callWithRetry(url, init, attempt + 1); } ``` ## Designing under the limit - **Batch instead of looping.** Twenty requests in a `for` loop become one request that takes a list. - **Cache reads.** `ctx.redis` with a short TTL removes most repeat traffic. - **Poll slower than you think you need.** Ten seconds is usually indistinguishable from one for a human watching a screen. - **Do not retry a 429 immediately.** Back off. ## Next - [Public routes](/edge/public-routes): why they share a budget. - [Errors](/edge/errors): every code, including these three. --- # Errors URL: https://docs.fenaura.dev/edge/errors Section: Edge functions # Errors Errors come from two places: the runtime, before your code runs, and your own handler. The code tells you which. ## Runtime errors These are produced before your function executes. Your code cannot catch them and does not need to, the fix is always configuration or the caller. ### `401 SESSION_MISSING` No session on a private route. Every route is session-gated before your code runs, so this is returned instead of your handler being called. **Fix:** sign in, or send `Authorization: Bearer `. If the caller is a script, it must hold a real session; there is no way to skip the check on a private route. If the route should be open, declare it public deliberately, see [Public routes](/edge/public-routes). ### `401 SESSION_INVALID` A session was presented but is not valid, expired, malformed, or unverifiable. **Fix:** sign in again to obtain a fresh session. ### `401 SESSION_CONFLICT` Two session cookies that disagree. **Fix:** clear cookies for the site and sign in again. Usually follows a domain change or holding a development and a production session simultaneously. ### `401 DEV_ACCESS_DENIED` A development URL was called without a dev key and without an active development session. **Fix:** sign in as an approved development user (`credentials: 'include'`), send the `X-Fenaura-Dev-Key` header from server/CLI tests, or call the production Fleet URL. ### `403 EMAIL_NOT_VERIFIED` The project requires verified emails and this user has not verified. **Fix:** complete verification, or turn the requirement off while developing. ### `404 NOT_FOUND` No route matches, or no function is deployed. **Fix:** check the path against your routes, and check that the append is direct, `/api/notes`, not `/default/api/notes`. ### `429 PROJECT_THROTTLED` More than 1000 requests in 10 seconds for this project. **Fix:** batch, cache, or poll slower. On a public route this budget is shared by every visitor. ### `429 USER_THROTTLED` More than 200 requests in 10 seconds from one end user. **Fix:** this is nearly always a polling loop with no backoff. Fix the client. ### `429 PREVIEW_THROTTLED` Preview runs exceeded: 60 in a minute per developer, 30 per IP. **Fix:** wait. This limit exists because a preview run costs real compute. ## Your own errors Return the right status and a code, and log `ctx.requestId` so it can be found later: ```ts // main.ts export default async (req: any, ctx: any) => { try { const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {}); if (!body?.title) { return ctx.json( { error: 'A title is required', code: 'TITLE_REQUIRED', requestId: ctx.requestId }, 400, ); } // ... } catch (e) { console.error('notes handler failed', ctx.requestId, e); return ctx.json( { error: 'Something went wrong', code: 'INTERNAL', requestId: ctx.requestId }, 500, ); } }; ``` Do not return a 200 with `{ error }` inside. A caller checking `res.ok` will treat the failure as a success, and the bug surfaces somewhere far away. ## Status codes to use | Status | When | |---|---| | 400 | The caller sent something malformed | | 401 | Not signed in (the runtime usually does this for you) | | 403 | Signed in, not allowed | | 404 | The thing does not exist | | 409 | Conflict, such as a duplicate | | 422 | Well-formed but semantically wrong | | 429 | Rate limited | | 500 | Your bug | ## A failed request leaves no trace An unauthenticated request to a private route produces no log line from your code, because your code did not run. When you are convinced a handler should have fired and see nothing, check the status code for `401` before reading the handler. ## Next - [Rate limits](/edge/rate-limits): the numbers behind the 429s. - [Authentication troubleshooting](/auth/troubleshooting): the 401s. --- # Storage URL: https://docs.fenaura.dev/storage Section: Storage # Storage Files live in buckets. A bucket belongs to the project, and every file in it is addressed by a path you choose. ## Uploading ```ts const { data, error } = await fenaura.storage .from('avatars') .upload(`users/${userId}.png`, file, { compress: true, onProgress: (percent) => console.log(`${percent}%`), }); ``` Uploads are chunked, so a large file resumes after a dropped connection instead of starting again. Chunks retry individually, which is what makes a 40 MB video over a phone connection behave. ### Options | Option | Default | Notes | |---|---|---| | `compress` | `false` | Images resize to a max of 1920px at quality 0.8; other files gzip | | `onProgress` | none | Receives a 0-100 number | | `upsert` | `false` | Overwrite an existing path | The upload cap is 50 MiB by default, and it applies after compression, so `compress: true` genuinely lets a bigger source photo through. ## Reading a file Three ways, and the choice is a security decision: ### Session-gated ```ts const { data } = await fenaura.storage.from('avatars').download(path); ``` The request carries the caller's session, so it works only for a signed-in end user. This is the default, and the right choice for anything private. ### Public ```ts // A stable anonymous link. Public buckets only. const { data } = await fenaura.storage.from('avatars').createPublicUrl(path); // data.public_url ``` Anyone with the URL can read it, signed in or not. Only for files you would put on a public web page, a logo, a marketing image. The link never expires, so treat it like publishing, not like sharing. (The session-gated `getPublicUrl` builds the URL your own app uses instead, and outsiders who fetch it directly get a 401.) ### Signed ```ts const { data } = await fenaura.storage .from('invoices') .createSignedUrl(path, 3600); // seconds ``` A time-limited URL that works without a session. Use it for "share this file" and for anything an outside service needs to fetch. Signed URLs are capped at seven days; a longer lifetime defeats the purpose. ## Listing ```ts const { data: files } = await fenaura.storage .from('avatars') .list({ prefix: `users/`, limit: 100 }); ``` `prefix` filters by path, which is why a structured path like `users/.png` pays off, it makes listing and access rules simple. ## Deleting ```ts await fenaura.storage.from('avatars').remove([`users/${userId}.png`]); ``` Deleting is immediate and permanent. There is no trash. ## Choosing an access model | The file | Use | |---|---| | Is public content, same for everyone | Public URL | | Belongs to one end user | Session-gated | | Must be fetched by an outside service | Signed URL | | Is sensitive and rarely needed | Session-gated, with a signed URL when sharing | ## Sizes and limits | Limit | Value | |---|---| | Upload cap | 50 MiB (after compression) | | Chunk size | 1 MiB | | Signed URL lifetime | Max 7 days | ## Next - [Uploading](/storage/uploading): chunking, retry, compression detail. - [Access control](/storage/access): the three read models in depth. --- # Uploading URL: https://docs.fenaura.dev/storage/uploading Section: Storage # Uploading An upload is split into 1 MiB chunks. Each chunk is sent, retried on failure, and acknowledged individually. The platform assembles the file when the last chunk arrives. ```render img:docs-chunked-upload-flow|A large file is optionally compressed, split into chunks sent in parallel with per-chunk retry, reassembled by storage, and acknowledged with a path, bucket and size envelope ``` ## The call ```ts const { data, error } = await fenaura.storage .from('videos') .upload(`raw/${videoId}.mp4`, file, { compress: false, upsert: false, onProgress: (percent) => setProgress(percent), }); if (error) { // the upload did not complete; nothing is stored } ``` The resolved shape is the same envelope the query builder returns, with the stored file's details in `data`: ```json { "status": "success", "data": { "path": "raw/clip-42.mp4", "bucket": "videos", "size": 1048576, "content_type": "video/mp4" }, "error": null, "request_id": "5ef93bb7-093d-4e13-9b1d-d41d27bf2f04" } ``` When you uploaded with `compress: true` and the file actually shrank, a `compression` object joins `data` with `mode`, `original_size` and `compressed_size`. Client-side problems (a path that tries to escape the bucket, a file over 50 MiB, an empty file) throw synchronously before any bytes move; server problems come back in `error` with a code such as `ALREADY_EXISTS` when the path is taken and you did not pass `upsert: true`. Either the whole file lands or nothing does. A partial upload is not left behind for you to clean up. ## Why chunking matters On a good connection a single request is fine. On a phone moving between networks, a single request fails at 90 percent and starts again from zero. With chunks, the failed chunk is the only thing resent. You do not manage this. It is what the upload does. ## Progress `onProgress` receives a number from 0 to 100 across the whole file, not per chunk. Throttle your own rendering, a state update per byte will melt the UI: ```ts let last = 0; onProgress: (pct) => { if (pct - last >= 2 || pct === 100) { last = pct; setProgress(pct); } }, ``` ## Compression With `compress: true`: - **Images** are resized to a maximum of 1920px on the long edge and re-encoded at quality 0.8, keeping the format where it can. - **Other files** are gzipped. Compression happens before the cap is applied, so a 60 MiB photo that compresses to 4 MiB uploads without complaint. A 60 MiB zip that is already compressed does not fit, and returns an error naming the limit. Leave `compress` off for formats where re-encoding loses quality you care about, video, already-optimised images, and anything you will process yourself. ## Overwriting By default an upload to an existing path **fails**. That is deliberate: a second upload cannot silently replace the first. ```ts .upload(path, file, { upsert: true }) ``` Use `upsert: true` for a profile picture where the path never changes, and leave it off everywhere else. A versioned path (`users//.png`) makes the whole question disappear and gives you history for free. ## Somebody else uploaded the same path A concurrent upload to one path with `upsert: false` fails rather than racing. The second caller gets an error and can retry with a new path. This is a conflict report, not corruption. ## Verifying an upload After success, confirm what landed: ```ts const { data } = await fenaura.storage.from('videos').list({ prefix: `raw/${videoId}` }); ``` Check the size and the name. An upload that reported success but stored zero bytes is almost always a file object that was already consumed, a `Blob` from a form can only be read once if something else read it first. ## Without the SDK (plain HTTP `fetch`) You can run the exact same 3-step upload (`POST /blob/:projectId/init`, `PUT /blob/:projectId/chunk/:uploadId/:index`, `POST /blob/:projectId/complete/:uploadId`) from any language, framework, or mobile client. See [Pure fetch & mobile API](/sdk/fetch#4-storage-uploads-downloads-and-signed-urls-over-http) for copy-paste examples. ## Next - [Access control](/storage/access): how the file is read back. - [Managing files](/storage/managing): list, move, delete. - [Pure fetch & mobile API](/sdk/fetch): chunked upload and signed URLs without the SDK. --- # Access control URL: https://docs.fenaura.dev/storage/access Section: Storage # Access control A file's access model is decided by how you produce the link. There are three, and each proves something different. ```render img:docs-storage-access-levels|Three ways to link a file: session-gated links require a signed-in caller, public links work for anyone forever, and signed URLs work for anyone until they expire ``` ## Session-gated ```ts const { data } = await fenaura.storage.from('invoices').download(path); ``` The request carries the caller's session, so the platform knows who is asking. This is the right default for anything private. It proves *someone signed in*, not *this person may see this file*. If the file belongs to one user, the bucket path and your own check must enforce that: ```ts const path = `invoices/${userId}/${invoiceId}.pdf`; ``` Scoping by user id in the path means a guessed path is another user's file, which you then refuse. Do not rely on an unguessable name alone. ## Public ```ts // A same-origin URL that resolves for the signed-in caller of your app const url = fenaura.storage.from('avatars').getPublicUrl(path); // A stable anonymous link. Public buckets only. const { data } = await fenaura.storage.from('avatars').createPublicUrl(path); // data.public_url ``` These are two different things with one idea behind them: content that does not need a session to view. `getPublicUrl` builds the URL your app itself will use. It resolves because the caller carries a session; an outsider fetching it directly gets a 401. Use it for images and files your signed-in users load on every page. `createPublicUrl` mints a link that works for anyone, forever, with no session. It only works on buckets whose read access is "anyone". Use it for content you would happily put on a public page. Two consequences people miss with a truly public link: - **The link does not expire.** Once it is out, it is out. - **Search engines can find it.** A public URL in an HTML page is indexable. That is correct for a logo and wrong for a tax document. ## Signed URLs ```ts const { data } = await fenaura.storage .from('invoices') .createSignedUrl(path, 3600); ``` A signed URL carries a time-limited signature. It works without a session for the number of seconds you choose, up to seven days. Producing it requires a session, so a signed URL is what you hand out to something that has no session: an email recipient, a webhook receiver, a third-party renderer. ```ts // Share a document with a client for an hour const { data } = await fenaura.storage.from('invoices').createSignedUrl(path, 3600); await sendEmail({ to: client.email, link: data.signedUrl }); ``` ## Choosing | Question | Answer | Use | |---|---|---| | Is it the same for everyone? | Yes | Public | | Does an outside system need to fetch it? | Yes | Signed | | Is it private to one end user? | Yes | Session-gated | | Is it private but occasionally shared? | Both | Session-gated, signed on share | ## Mistakes worth avoiding **A public bucket with private files in it.** Decide per bucket, and make the bucket name say which it is: `public-assets` versus `user-uploads`. **Signed URLs that live forever.** A seven-day link mailed to a customer is a permanent leak with a date on it. Use minutes for anything sensitive. **Trusting the path.** An unguessable name is obscurity, not access control. Sign it or gate it. **Checking in the frontend.** Hiding a download button is not access control. The file is one `curl` away. ## Next - [Managing files](/storage/managing): list and delete. - [Security and RLS](/database/security): the same reasoning for rows. --- # Managing files URL: https://docs.fenaura.dev/storage/managing Section: Storage # Managing files ## Listing ```ts const { data: files } = await fenaura.storage .from('avatars') .list({ prefix: 'users/', limit: 100, offset: 0 }); ``` `prefix` filters by the start of the path. There are no real directories, a path is a string, and a prefix is a string match. That is why consistent paths matter: ``` users/abc/avatar.png users/abc/invoices/2026-01.pdf ``` Listing `users/abc/` returns that user's files. Listing `users/` returns everything under any user. Without a scheme, you are listing the whole bucket and filtering in memory. ## Paginating ```ts const all: FileObject[] = []; let offset = 0; while (true) { const { data: page } = await fenaura.storage .from('documents') .list({ prefix: 'reports/', limit: 100, offset }); all.push(...page); if (page.length < 100) break; offset += 100; } ``` Stop when a page comes back short. An empty page means you are done. ## Downloading ```ts const { data: blob } = await fenaura.storage.from('avatars').download(path); ``` For a large file, prefer a URL over a download through the SDK: ```ts const { data } = await fenaura.storage.from('videos').createSignedUrl(path, 300); window.location.href = data.signedUrl; ``` The browser then streams the file directly, with its own progress and resume, instead of your code buffering it in memory. ## Deleting ```ts await fenaura.storage.from('avatars').remove([`users/${userId}/avatar.png`]); ``` `remove` takes an array. Deleting is immediate and permanent. Deleting a row that points at a file does not delete the file. Decide which side owns the lifecycle: - **Row owns the file.** Delete the file when the row is deleted, and nothing else creates a file without a row. - **File is independent.** Deleting the row leaves the file, and a cleanup job finds orphans. Pick one. Doing both halfway is how buckets fill with unreferenced files. ## A path scheme that works Put the owner first, then the kind, then the name: ``` // ``` It makes three things trivial: listing one owner's files, writing an access rule, and finding the file an error message is talking about. ## Next - [Access control](/storage/access): how each file gets read. - [Quotas](/platform/quotas): storage limits. --- # Email URL: https://docs.fenaura.dev/email Section: Email # Email A project can send email: account verification, password resets, welcome messages, and your own transactional or broadcast mail. ```render img:docs-email-delivery-pipeline|Email flows from your Fleet through the Fenaura dispatcher, which signs it, through the SPF, DKIM and DMARC checkpoint to the recipient inbox; missing DNS records route it to spam instead ``` ## The two kinds **Transactional** is one message to one person, triggered by something they did. It must arrive and it must not wait: a verification email delayed by ten minutes is a broken sign-up. **Broadcast** is one message to many people. It can be queued, it needs an unsubscribe path, and it is subject to bulk-sender rules. Mixing them is the classic mistake, sending a product update through the transactional path gets your domain flagged and your password resets stop arriving. ## Templates The project ships with templates for the flows that must work on day one: | Template | Sent when | |---|---| | Verification code | Signing up, if verification is required | | Password reset | A user requests a reset | | Magic link | Passwordless sign-in | | Welcome | Optional (off by default); enable in **Email › Settings** to send after a user signs up and verifies | | Sign-in alert | Optional (off by default); enable in **Email › Settings** to notify a user with time, IP, approximate location, and device on every sign-in | | Team invitation | You invite a collaborator | Edit them in the dashboard. Each holds variables such as `{{code}}`, `{{project_name}}` and `{{expires_in}}`, filled in when the mail is sent. Every template has a plain-text and an HTML body. Send both, a text body is not optional for your best inbox placement. ## Sending From an edge function, transactional mail goes out through the project's configured provider: ```ts await sendEmail({ to: 'ada@example.com', subject: 'Your receipt', html: '

Thanks for your order.

', text: 'Thanks for your order.', }); ``` The provider is the one configured in the project's [email settings](https://fenaura.dev/app/projects/your-project-id/email?tab=settings), Brevo, or your own SMTP. You do not put an API key in your code; the platform holds it. If you run your own backend server (Node, Python, Go, Rust, etc.), copy your **Project slug** from **Settings › General** and your **Project API Key** from **Email › More › Developers** (or **Project Overview › Project Secret**), then call the email endpoint: ```ts const PROJECT_SLUG = 'my-app'; const PROJECT_SECRET_KEY = 'your-project-secret-key'; await fetch(`https://api.fenaura.dev/dp/projects/${PROJECT_SLUG}/email/send`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${PROJECT_SECRET_KEY}`, }, body: JSON.stringify({ to: 'ada@example.com', type: 'welcome', env: 'production', variables: { name: 'Ada' }, }), }); ``` Keep `PROJECT_SECRET_KEY` on your server only; never ship it in browser or mobile apps. ## Deliverability Mail that lands in spam is mail that failed. Four things decide it, in this order: 1. **Authentication.** SPF, DKIM and DMARC records on your sending domain. Without them, a mailbox provider cannot tell your mail from a forgery. 2. **Reputation.** Sending history on that domain. A new domain sending a thousand messages on day one looks like a spammer. 3. **Content.** A plain-text part, a real unsubscribe link, no link shorteners, and nothing that reads like a phishing template. 4. **List hygiene.** Sending to addresses that do not exist destroys reputation faster than any other single cause. Set up domain authentication before you send more than a handful of messages. Retrofitting it after your domain is flagged is much harder than starting with it. ## Next - [Direct API URLs Reference](/platform/direct-urls): every direct Fenaura URL for non-browser callers. - [Templates](/email/templates): editing and variables. - [Deliverability](/email/deliverability): SPF, DKIM, DMARC in practice. --- # Templates URL: https://docs.fenaura.dev/email/templates Section: Email # Templates Each template is the message for one flow. Editing it changes what the user receives; it does not change when it is sent. ## The variables These are available in the templates that support them: | Variable | Meaning | Available in | |---|---|---| | `{{code}}` | The verification or reset code | Verification, reset | | `{{email}}` | The user's address | All | | `{{project_name}}` | Your project's name, as the sender | All | | `{{expires_in}}` | How long the code lasts, in words | Code emails | | `{{verification_link}}` | The one-click link | Magic link, codes | | `{{tenant_name}}` | The organisation's name | Team invitation | | `{{role}}` | The role being granted | Team invitation | | `{{inviter}}` | Who sent the invitation | Team invitation | | `{{time}}` | UTC timestamp of the sign-in | Sign-in alert | | `{{ip}}` | Client IP address | Sign-in alert | | `{{location}}` | Formatted approximate city, region, and country | Sign-in alert | | `{{city}}`, `{{region}}`, `{{country}}` | Individual approximate location fields | Sign-in alert | | `{{latitude}}`, `{{longitude}}`, `{{coordinates}}` | Approximate coordinates when available | Sign-in alert | | `{{device}}`, `{{browser}}`, `{{os}}`, `{{user_agent}}` | Parsed device, browser, operating system, and raw User-Agent | Sign-in alert | An unknown variable is left as written, so a typo appears literally in a user's inbox. Send yourself a test after editing. ### Built-in sign-in alert (off by default) The **Sign-In Alert** template (`sign_in`) notifies end users whenever a new sign-in succeeds (password, magic link, or OAuth). It starts **off** so new projects do not send extra mail unexpectedly; flip **Send Sign-In Alert Email** in **Email › Settings** whenever you want it active. Like every other template, development sign-ins are trapped in the Mailmy inbox and never consume your production email allowance. ### Recovering variables in the editor Every template editor includes a **Variables** bar directly above the HTML code. Click any `{{variable}}` chip to copy it back into your template, or click **Restore default** to reset the subject and HTML body to Fenaura's built-in starting point without losing your other templates. ## The variables you must keep A verification email without `{{code}}` cannot be used. A magic link without `{{verification_link}}` cannot be clicked. When you redesign a template, keep the variable that carries the payload, everything else is yours to change. ## Editing safely 1. **Duplicate** the template before a large change, so you can return to it. It is in the row's ⋯ menu, and it works on the built-in templates too. 2. Keep `{{code}}` or `{{verification_link}}`, whichever the flow uses. 3. Keep a plain-text body. It affects inbox placement, not just accessibility. 4. Send a test to a real mailbox you own, on a real domain. 5. Check it on a phone. Most codes are read on a phone, and a code that wraps across two lines is a support ticket. ### Why duplicate is the first step A built-in template cannot be renamed or deleted. There is nothing to fall back to if you break it, because the platform ships it. Duplicating gives you a copy with its own slug (`verification-copy`, then `-copy2` if that is taken) that you own completely: rename it, rewrite it, delete it, and the original stays intact. The copy is seeded with the same subject and body the editor shows for the built-in, so you start from working content rather than a blank page. If the name is taken the create is refused with a conflict instead of quietly overwriting a template you already had. ## Development and production send differently This surprises people, so it is worth stating plainly: **the same template sends in both environments, but only one of them reaches a real mailbox.** | | Development | Production | | --- | --- | --- | | Delivery | Recorded only, never sent | Really sent through the provider | | Where you read it | The Mailmy inbox in the dashboard | The recipient's mailbox | | Costs email budget | No | Yes | | Domain or DNS needed | No | Yes | Development sends are **trapped**: the message is written to the outbox marked `trapped`, so you can open it, inspect the rendered HTML and check the code, while nothing leaves the platform. That is why you can develop a sign-up flow before DNS is set up, and why trapped sends never consume the monthly allowance. The consequence to remember: a trapped send proves your template *renders*, not that it *arrives*. Deliverability (SPF, DKIM, DMARC, sender reputation) is only tested by a production send to a mailbox you control. ## Creating a template with Veilo You can write a template by hand in the editor, or ask Veilo for one. Veilo writes into the same template store, so what it produces is a normal template: you can edit it afterwards, preview it, and send it. Be specific in the request, because Veilo cannot see your product: - **What the email is for** - "a password reset code", not "an email". - **Which variable to use**, and the exact name (`{{code}}`, `{{name}}`). - **Tone and length** - one line for a code, a few short paragraphs for a welcome. - **What the buttons should say**, and where they point. Always send the result to a real mailbox before it goes live. The rules that make HTML survive mail clients are on this page for that reason; a generated template is a first draft that respects them only if you check. ## Testing a template Send it with a real code path rather than pasting a fake one. Sign up with a test address and confirm the mail arrives, the code works, and the link opens the right page. A template that renders beautifully but sends a dead link passes every visual check. ## HTML that survives a mail client Mail clients are not browsers. Keep to these: - Inline styles only. No `