# AI Coding Agents Source: https://docs.modelence.com/ai-coding-agents Set up Claude Code, Cursor, or Codex to build Modelence apps locally Modelence apps follow framework conventions that a general-purpose coding agent doesn't know by default: [Stores](/stores) instead of raw MongoDB drivers, [`configSchema`](/configuration) instead of `process.env`, and typed [queries](/core-concepts/queries) and [mutations](/core-concepts/mutations) instead of `fetch('/api/...')` calls. Without guidance, an agent writes code that looks reasonable but works against the framework. This page shows how to give your local agent the same rules and documentation access that the Modelence App Builder uses in the cloud. ## Claude Code plugin The `modelence` plugin gives Claude Code: * **Framework rules**, always in context — database, configuration, authentication, and UI conventions. * **Skills**, loaded on demand — complete reference implementations of Modules, Stores, queries, mutations, and cron jobs, plus Expo Router rules for [React Native apps](/react-native). * **Live documentation access** through the Modelence docs MCP server, so the agent looks up APIs instead of writing them from memory. * **Database access** to your Modelence environments, after a one-time sign-in — see [Inspecting your environment](#inspecting-your-environment). It works everywhere Claude Code runs: the terminal CLI, the desktop app, and the VS Code and JetBrains extensions. ### Installing `npx modelence@latest setup` installs the plugin for you. After connecting the project it offers to install the plugin through the Claude Code CLI, which works the same whether you use Claude Code in the terminal, in VS Code or JetBrains, or in the Claude desktop app. Say yes and you're done. To install it yourself — or to reinstall it after it was removed — run these two commands in a terminal: ```bash theme={null} claude plugin marketplace add modelence/modelence claude plugin install modelence@modelence --scope project ``` If a Claude Code session is already open, run `/reload-plugins` in it or start a new session. To confirm, run `/plugin`: `modelence` should appear under installed plugins. > [!NOTE] > > The plugin requires Claude Code v2.1.195 or later, and the `claude` command on your PATH. The desktop > app and the IDE extensions ship a private copy that isn't on your PATH, so > `npx modelence@latest setup` can't use it — if `claude` isn't found, install the standalone CLI from > [code.claude.com](https://code.claude.com/docs/en/setup) first. ### Sign in to Modelence The plugin's `modelence` MCP server — the one that reads your environments — needs a one-time sign-in with your Modelence account. In Claude Code, run `/mcp`, choose `modelence`, then **Authenticate**. Your browser opens — sign in and choose the organization your app belongs to. Claude Code stores the sign-in per server, so it covers every Modelence project on your machine. Until you sign in, Claude Code lists the server as needing authentication and its tools are unavailable; the rest of the plugin works regardless. See [Inspecting your environment](#inspecting-your-environment) for what the sign-in grants. ### Sharing it with your team Setup also writes a `.claude/settings.json` to the project, which tells Claude Code where the plugin comes from. Commit it: teammates who open the project are prompted to install the plugin, and running `npx modelence@latest setup` on their clone installs it for them. This is what the file contains: ```json .claude/settings.json theme={null} { "extraKnownMarketplaces": { "modelence": { "source": { "source": "github", "repo": "modelence/modelence" } } }, "enabledPlugins": { "modelence@modelence": true } } ``` The setting is project-scoped — it doesn't affect your other projects. ## The local workflow A few conventions are worth knowing about, since they shape how sessions behave: * **The agent runs the dev server.** If nothing is already serving your app, it starts `npm run dev` in the background (port 3000 by default, restarting on file changes) and reads the output, so it catches runtime errors and not just type errors. You don't need to run any commands yourself. * **It won't fight a server you started.** If you're already running `npm run dev` in your own terminal, the agent uses that one instead of starting a second. In that case the logs belong to your terminal and the agent can't read them — paste any errors you want it to fix. * **Type checking is part of finishing.** The agent runs `npx tsc --noEmit` and fixes all errors before reporting work as done. * **Your local files are the source of truth.** Everything happens in your working copy, not in a cloud sandbox. * **`.modelence.env` is left alone.** It connects your project to its Modelence Cloud environment, including the MongoDB database — see [Setup](/setup). * **Some things need the dashboard.** [Config values](/configuration), [authentication providers](/authentication), [email providers](/email/providers), [user roles](/roles), database connections, and [file storage](/files) are set up in Modelence Cloud. The agent makes the code-side change and points you to the right dashboard page for the rest. ## Docs access for any agent The Modelence documentation is available as a hosted MCP server that requires no authentication. The Claude Code plugin registers it for you; add it manually for other tools. ```bash Claude Code theme={null} claude mcp add --transport http modelence-docs https://docs.modelence.com/mcp ``` ```json Other MCP clients theme={null} { "mcpServers": { "modelence-docs": { "type": "http", "url": "https://docs.modelence.com/mcp" } } } ``` It exposes `search_modelence` for searching the documentation, `query_docs_filesystem_modelence` for reading specific pages, and `submit_feedback` for reporting gaps in the docs. For agents without MCP support, the documentation is also published in plain text: * [`docs.modelence.com/llms.txt`](https://docs.modelence.com/llms.txt) — an index of every page * [`docs.modelence.com/llms-full.txt`](https://docs.modelence.com/llms-full.txt) — the full documentation as a single file ## Other agents Cursor, Codex, and most other agents read an `AGENTS.md` file from the project root. Apps generated by the App Builder already include one covering the framework conventions. For projects created with the CLI, add your own `AGENTS.md` describing the conventions your project relies on, and point the agent at `llms.txt` for the rest. Then register the docs MCP server through your tool's own MCP configuration, using the JSON above. ## Deploying any Node.js app Modelence Cloud also hosts projects that don't use the framework — an Express API, a Vite site, a Next.js app. How such a project is built and run is described in a `modelence.config.json` file at its root, and your agent is the right one to write it, since it knows the codebase. Give it the [Deploy Setup](/deploy/setup) page — it is written for agents and covers the file's reference, worked examples, and how to verify the result locally — then run `npx modelence@latest deploy`: ```text theme={null} Use https://docs.modelence.com/deploy/setup.md to set up Modelence deployment for this project ``` ## Inspecting your environment Your project is connected to a Modelence environment, and the agent can query its database directly — the same MongoDB your local app reads and writes. That makes it useful for diagnosis: confirming what a mutation actually stored, checking a migration's result, or inspecting a document's real shape. This needs the one-time [sign-in](#sign-in-to-modelence) described above. The sign-in grants access to all apps in the organization you chose — the agent reads `MODELENCE_ENVIRONMENT_ID` from `.modelence.env` to work against the environment this project is connected to, and can look at your other environments and apps when you ask it to, which is handy for comparing against production or borrowing context from a related app. > [!NOTE] > > If you switch environments by re-running `npx modelence@latest setup`, start a new agent session so > it picks up the new environment id. There's nothing to reconnect — the sign-in stays valid. ### From other clients The same server is available at `https://cloud.modelence.com/mcp` for tools that aren't running inside your project — claude.ai on web or mobile, Cursor, Codex, or a Claude Code session outside a project directory. The browser sign-in is the same, and grants access to every app in your organization, including status and logs for App Builder sandboxes: ```bash theme={null} claude mcp add --transport http modelence https://cloud.modelence.com/mcp ``` You don't need this inside a Modelence project — the plugin already registers the server. ## Next steps > [card] [Project Structure](/core-concepts/project-structure) > > How a Modelence project is laid out > [card] [Modules](/core-concepts/modules) > > The building block agents work with most # generateText Source: https://docs.modelence.com/api-reference/@modelence/ai/functions/generateText [API Reference](/api-reference/@modelence/ai/functions/../../../index) / [@modelence/ai](/api-reference/@modelence/ai/functions/../index) / generateText > **generateText**(`options`): `Promise`\<`GenerateTextResult`\<`ToolSet`, `Output`\<`any`, `any`, `any`>>> Defined in: [index.ts:77](https://github.com/modelence/modelence/blob/main/packages/ai/src/index.ts#L77) Generates text using AI models with built-in Modelence configuration and telemetry. This is a wrapper around the AI SDK's generateText function that automatically configures providers using Modelence's server-side configuration system. ## Example ```typescript theme={null} import { generateText } from '@modelence/ai'; const response = await generateText({ provider: 'anthropic', model: 'claude-sonnet-4-6', messages: [ { role: 'user', content: 'Write a haiku about programming' } ], temperature: 0.7 }); console.log(response.text); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | [`GenerateTextOptions`](/api-reference/@modelence/ai/functions/../type-aliases/GenerateTextOptions) | Configuration options for text generation | ## Returns `Promise`\<`GenerateTextResult`\<`ToolSet`, `Output`\<`any`, `any`, `any`>>> A promise that resolves to the generated text result # @modelence/ai Source: https://docs.modelence.com/api-reference/@modelence/ai/index [API Reference](/api-reference/@modelence/ai/../../index) / @modelence/ai ## Type Aliases * [GenerateTextOptions](/api-reference/@modelence/ai/type-aliases/GenerateTextOptions) ## Functions * [generateText](/api-reference/@modelence/ai/functions/generateText) # GenerateTextOptions Source: https://docs.modelence.com/api-reference/@modelence/ai/type-aliases/GenerateTextOptions [API Reference](/api-reference/@modelence/ai/type-aliases/../../../index) / [@modelence/ai](/api-reference/@modelence/ai/type-aliases/../index) / GenerateTextOptions > **GenerateTextOptions** = `ModelenceGenerateTextOptions`\<`OriginalGenerateTextParams`> Defined in: [index.ts:28](https://github.com/modelence/modelence/blob/main/packages/ai/src/index.ts#L28) Options for the Modelence generateText function. This type extends all the standard AI SDK generateText options, but replaces the model parameter with separate provider and model parameters. # @modelence/auth-ui Source: https://docs.modelence.com/api-reference/@modelence/auth-ui/index [API Reference](/api-reference/@modelence/auth-ui/../../index) / @modelence/auth-ui # @modelence/auth-ui Authentication UI components for Modelence. ## Installation ```sh theme={null} npm install @modelence/auth-ui ``` ## Setup Add this package to your `tailwind.config.js` content paths: ```js theme={null} /** @type {import('tailwindcss').Config} */ module.exports = { content: [ ..., "./node_modules/@modelence/auth-ui/dist/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], } ``` That's it! The components use standard Tailwind classes and will work with your existing Tailwind setup. ## Usage ```tsx theme={null} import { LoginForm } from '@modelence/auth-ui'; function AuthPage() { return ( ( {children} )} /> ); } ``` ## Customization You can customize the appearance using className props: ```tsx theme={null} ( {children} )} /> ``` ## Framework Support This library is framework-agnostic but includes special support for navigation: ### Next.js ```tsx theme={null} import Link from 'next/link'; import { LoginForm } from '@modelence/auth-ui'; ( {children} )} /> ``` ### React Router ```tsx theme={null} import { Link } from 'react-router-dom'; import { LoginForm } from '@modelence/auth-ui'; ( {children} )} /> ``` ## Development To build the package: ```sh theme={null} npm run build ``` To watch for changes during development: ```sh theme={null} npm run dev ``` # sendEmail Source: https://docs.modelence.com/api-reference/@modelence/aws-ses/functions/sendEmail [API Reference](/api-reference/@modelence/aws-ses/functions/../../../index) / [@modelence/aws-ses](/api-reference/@modelence/aws-ses/functions/../index) / sendEmail > **sendEmail**(`payload`): `Promise`\<`void`> Defined in: [index.ts:83](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L83) Sends an email via Resend. ## Example ```ts theme={null} import { sendEmail } from '@modelence/aws-ses'; sendEmail({ from: 'test@example.com', to: 'test@example.com', subject: 'Test Email', html: '

Hello World

' }) ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `payload` | [`EmailPayload`](/api-reference/@modelence/aws-ses/functions/../type-aliases/EmailPayload) | The email payload object. | ## Returns `Promise`\<`void`> # @modelence/aws-ses Source: https://docs.modelence.com/api-reference/@modelence/aws-ses/index [API Reference](/api-reference/@modelence/aws-ses/../../index) / @modelence/aws-ses ## Type Aliases * [EmailAttachment](/api-reference/@modelence/aws-ses/type-aliases/EmailAttachment) * [EmailPayload](/api-reference/@modelence/aws-ses/type-aliases/EmailPayload) ## Variables * [default](/api-reference/@modelence/aws-ses/variables/default) ## Functions * [sendEmail](/api-reference/@modelence/aws-ses/functions/sendEmail) # EmailAttachment Source: https://docs.modelence.com/api-reference/@modelence/aws-ses/type-aliases/EmailAttachment [API Reference](/api-reference/@modelence/aws-ses/type-aliases/../../../index) / [@modelence/aws-ses](/api-reference/@modelence/aws-ses/type-aliases/../index) / EmailAttachment > **EmailAttachment** = `object` Defined in: [index.ts:10](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L10) ## Properties | Property | Type | Defined in | | - | - | - | | `content` | `Buffer` \| `string` | [index.ts:12](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L12) | | `contentType` | `string` | [index.ts:13](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L13) | | `filename` | `string` | [index.ts:11](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L11) | # EmailPayload Source: https://docs.modelence.com/api-reference/@modelence/aws-ses/type-aliases/EmailPayload [API Reference](/api-reference/@modelence/aws-ses/type-aliases/../../../index) / [@modelence/aws-ses](/api-reference/@modelence/aws-ses/type-aliases/../index) / EmailPayload > **EmailPayload** = `object` & \{ `html`: `string`; } | \{ `text`: `string`; } Defined in: [index.ts:16](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L16) ## Type declaration | Name | Type | Defined in | | - | - | - | | `attachments?` | [`EmailAttachment`](/api-reference/@modelence/aws-ses/type-aliases/EmailAttachment)\[] | [index.ts:26](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L26) | | `bcc?` | `string` \| `string`\[] | [index.ts:23](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L23) | | `cc?` | `string` \| `string`\[] | [index.ts:22](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L22) | | `from` | `string` | [index.ts:17](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L17) | | `headers?` | `Record`\<`string`, `string`> | [index.ts:25](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L25) | | `html?` | `string` | [index.ts:20](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L20) | | `replyTo?` | `string` \| `string`\[] | [index.ts:24](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L24) | | `subject` | `string` | [index.ts:19](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L19) | | `text?` | `string` | [index.ts:21](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L21) | | `to` | `string` \| `string`\[] | [index.ts:18](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L18) | # default Source: https://docs.modelence.com/api-reference/@modelence/aws-ses/variables/default [API Reference](/api-reference/@modelence/aws-ses/variables/../../../index) / [@modelence/aws-ses](/api-reference/@modelence/aws-ses/variables/../index) / default > **default**: `EmailProvider` Defined in: [index.ts:119](https://github.com/modelence/modelence/blob/main/packages/aws-ses/src/index.ts#L119) # NextServer Source: https://docs.modelence.com/api-reference/@modelence/next/classes/NextServer [API Reference](/api-reference/@modelence/next/classes/../../../index) / [@modelence/next](/api-reference/@modelence/next/classes/../index) / NextServer Defined in: [index.ts:11](https://github.com/modelence/modelence/blob/main/packages/next/src/index.ts#L11) Next.js server implementation for Modelence applications. This class wraps Next.js to provide a compatible server interface for the Modelence framework. ## Implements * `AppServer` ## Constructors ### Constructor > **new NextServer**(): `NextServer` #### Returns `NextServer` ## Methods ### handler() > **handler**(`req`, `res`): `void` Defined in: [index.ts:30](https://github.com/modelence/modelence/blob/main/packages/next/src/index.ts#L30) Handle incoming HTTP requests using Next.js. #### Parameters | Parameter | Type | Description | | - | - | - | | `req` | `Request` | Express request object | | `res` | `Response` | Express response object | #### Returns `void` #### Implementation of `AppServer.handler` *** ### init() > **init**(): `Promise`\<`void`> Defined in: [index.ts:17](https://github.com/modelence/modelence/blob/main/packages/next/src/index.ts#L17) Initialize the Next.js application and prepare the request handler. #### Returns `Promise`\<`void`> #### Implementation of `AppServer.init` # @modelence/next Source: https://docs.modelence.com/api-reference/@modelence/next/index [API Reference](/api-reference/@modelence/next/../../index) / @modelence/next ## Classes * [NextServer](/api-reference/@modelence/next/classes/NextServer) ## Variables * [nextServer](/api-reference/@modelence/next/variables/nextServer) # nextServer Source: https://docs.modelence.com/api-reference/@modelence/next/variables/nextServer [API Reference](/api-reference/@modelence/next/variables/../../../index) / [@modelence/next](/api-reference/@modelence/next/variables/../index) / nextServer > `const` **nextServer**: [`NextServer`](/api-reference/@modelence/next/variables/../classes/NextServer) Defined in: [index.ts:54](https://github.com/modelence/modelence/blob/main/packages/next/src/index.ts#L54) Pre-configured Next.js server instance for Modelence applications. Use this instance in your Modelence server configuration: ## Example ```typescript theme={null} import { startApp } from 'modelence/server'; import { nextServer } from '@modelence/next'; startApp({ server: nextServer }); ``` # ModelenceQueryClient Source: https://docs.modelence.com/api-reference/@modelence/react-query/classes/ModelenceQueryClient [API Reference](/api-reference/@modelence/react-query/classes/../../../index) / [@modelence/react-query](/api-reference/@modelence/react-query/classes/../index) / ModelenceQueryClient Defined in: [index.ts:39](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L39) Client for managing Modelence live queries with TanStack Query. Create one instance and connect it to your QueryClient. ## Example ```tsx theme={null} import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ModelenceQueryClient } from '@modelence/react-query'; const queryClient = new QueryClient(); new ModelenceQueryClient().connect(queryClient); function App() { return ( ); } ``` ## Constructors ### Constructor > **new ModelenceQueryClient**(): `ModelenceQueryClient` #### Returns `ModelenceQueryClient` ## Methods ### connect() > **connect**(`queryClient`): `void` Defined in: [index.ts:44](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L44) Connects to a TanStack Query QueryClient. This enables live query subscriptions and cache updates. #### Parameters | Parameter | Type | | - | - | | `queryClient` | `QueryClient` | #### Returns `void` # createQueryKey Source: https://docs.modelence.com/api-reference/@modelence/react-query/functions/createQueryKey [API Reference](/api-reference/@modelence/react-query/functions/../../../index) / [@modelence/react-query](/api-reference/@modelence/react-query/functions/../index) / createQueryKey > **createQueryKey**\<`T`, `U`>(`methodName`, `args`): [`ModelenceQueryKey`](/api-reference/@modelence/react-query/functions/../type-aliases/ModelenceQueryKey)\<`T`, `U`> Defined in: [index.ts:279](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L279) Utility function to create query keys for manual cache operations ## Example ```tsx theme={null} import { useQueryClient } from '@tanstack/react-query'; import { createQueryKey } from '@modelence/react-query'; function TodoActions() { const queryClient = useQueryClient(); const refreshTodos = () => { queryClient.invalidateQueries({ queryKey: createQueryKey('todo.getAll', { limit: 10 }) }); }; } ``` ## Type Parameters | Type Parameter | Default type | | - | - | | `T` *extends* `string` | - | | `U` *extends* `Args` | `Args` | ## Parameters | Parameter | Type | Description | | - | - | - | | `methodName` | `T` | The method name | | `args` | `U` | The arguments | ## Returns [`ModelenceQueryKey`](/api-reference/@modelence/react-query/functions/../type-aliases/ModelenceQueryKey)\<`T`, `U`> Typed query key # modelenceLiveQuery Source: https://docs.modelence.com/api-reference/@modelence/react-query/functions/modelenceLiveQuery [API Reference](/api-reference/@modelence/react-query/functions/../../../index) / [@modelence/react-query](/api-reference/@modelence/react-query/functions/../index) / modelenceLiveQuery > **modelenceLiveQuery**\<`T`>(`methodName`, `args`): `object` Defined in: [index.ts:146](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L146) Creates query options for live queries with TanStack Query's useQuery hook. Data will be updated in real-time when underlying data changes. Requires ModelenceQueryClient to be connected to your QueryClient. ## Example ```tsx theme={null} import { useQuery } from '@tanstack/react-query'; import { modelenceLiveQuery } from '@modelence/react-query'; function TodoList() { // Subscribe to live updates - data refreshes automatically when todos change const { data: todos } = useQuery(modelenceLiveQuery('todo.getAll', { userId })); return (
    {todos?.map(todo =>
  • {todo.title}
  • )}
); } ``` ## Type Parameters | Type Parameter | Default type | Description | | - | - | - | | `T` | `unknown` | The expected return type of the query | ## Parameters | Parameter | Type | Description | | - | - | - | | `methodName` | `string` | The name of the method to query | | `args` | `Args` | Optional arguments to pass to the method | ## Returns `object` Query options object for TanStack Query's useQuery | Name | Type | Default value | Defined in | | - | - | - | - | | `gcTime` | `number` | `0` | [index.ts:207](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L207) | | `queryFn()` | () => `Promise`\<`T`> | - | [index.ts:155](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L155) | | `queryKey` | readonly \[`"live"`, `string`, `Args`] | - | [index.ts:154](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L154) | | `refetchOnMount` | `boolean` | `false` | [index.ts:205](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L205) | | `refetchOnReconnect` | `boolean` | `false` | [index.ts:206](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L206) | | `refetchOnWindowFocus` | `boolean` | `false` | [index.ts:204](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L204) | | `staleTime` | `number` | `Infinity` | [index.ts:203](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L203) | # modelenceMutation Source: https://docs.modelence.com/api-reference/@modelence/react-query/functions/modelenceMutation [API Reference](/api-reference/@modelence/react-query/functions/../../../index) / [@modelence/react-query](/api-reference/@modelence/react-query/functions/../index) / modelenceMutation > **modelenceMutation**\<`T`>(`methodName`, `defaultArgs`): `object` Defined in: [index.ts:242](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L242) Creates mutation options for use with TanStack Query's useMutation hook. ## Example ```tsx theme={null} import { useMutation, useQueryClient } from '@tanstack/react-query'; import { modelenceMutation } from '@modelence/react-query'; function MyComponent() { const queryClient = useQueryClient(); // Basic usage const { mutate } = useMutation(modelenceMutation('todos.create')); // With additional options const { mutate: updateTodo } = useMutation({ ...modelenceMutation('todos.update'), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['todos.getAll'] }); }, }); return ; } ``` ## Type Parameters | Type Parameter | Default type | Description | | - | - | - | | `T` | `unknown` | The expected return type of the mutation | ## Parameters | Parameter | Type | Description | | - | - | - | | `methodName` | `string` | The name of the method to mutate | | `defaultArgs` | `Args` | Optional default arguments to merge with mutation variables | ## Returns `object` Mutation options object for TanStack Query's useMutation | Name | Type | Defined in | | - | - | - | | `mutationFn()` | (`variables`) => `Promise`\<`T`> | [index.ts:247](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L247) | # modelenceQuery Source: https://docs.modelence.com/api-reference/@modelence/react-query/functions/modelenceQuery [API Reference](/api-reference/@modelence/react-query/functions/../../../index) / [@modelence/react-query](/api-reference/@modelence/react-query/functions/../index) / modelenceQuery > **modelenceQuery**\<`T`>(`methodName`, `args`): `object` Defined in: [index.ts:108](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L108) Creates query options for use with TanStack Query's useQuery hook. ## Example ```tsx theme={null} import { useQuery } from '@tanstack/react-query'; import { modelenceQuery } from '@modelence/react-query'; function MyComponent() { // Basic usage const { data } = useQuery(modelenceQuery('todo.getAll')); // With additional options const { data: todo } = useQuery({ ...modelenceQuery('todo.getById', { id: '123' }), enabled: !!id, staleTime: 5 * 60 * 1000, }); return
{data?.name}
; } ``` ## Type Parameters | Type Parameter | Default type | Description | | - | - | - | | `T` | `unknown` | The expected return type of the query | ## Parameters | Parameter | Type | Description | | - | - | - | | `methodName` | `string` | The name of the method to query | | `args` | `Args` | Optional arguments to pass to the method | ## Returns `object` Query options object for TanStack Query's useQuery | Name | Type | Defined in | | - | - | - | | `queryFn()` | () => `Promise`\<`T`> | [index.ts:114](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L114) | | `queryKey` | (`string` \| `Args`)\[] | [index.ts:113](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L113) | # @modelence/react-query Source: https://docs.modelence.com/api-reference/@modelence/react-query/index [API Reference](/api-reference/@modelence/react-query/../../index) / @modelence/react-query ## Classes * [ModelenceQueryClient](/api-reference/@modelence/react-query/classes/ModelenceQueryClient) ## Type Aliases * [ModelenceQueryKey](/api-reference/@modelence/react-query/type-aliases/ModelenceQueryKey) ## Functions * [createQueryKey](/api-reference/@modelence/react-query/functions/createQueryKey) * [modelenceLiveQuery](/api-reference/@modelence/react-query/functions/modelenceLiveQuery) * [modelenceMutation](/api-reference/@modelence/react-query/functions/modelenceMutation) * [modelenceQuery](/api-reference/@modelence/react-query/functions/modelenceQuery) # ModelenceQueryKey Source: https://docs.modelence.com/api-reference/@modelence/react-query/type-aliases/ModelenceQueryKey [API Reference](/api-reference/@modelence/react-query/type-aliases/../../../index) / [@modelence/react-query](/api-reference/@modelence/react-query/type-aliases/../index) / ModelenceQueryKey > **ModelenceQueryKey**\<`T`, `U`> = readonly \[`T`, `U`] Defined in: [index.ts:254](https://github.com/modelence/modelence/blob/main/packages/react-query/src/index.ts#L254) Type helper for creating properly typed query keys ## Type Parameters | Type Parameter | Default type | | - | - | | `T` *extends* `string` | - | | `U` *extends* `Args` | `Args` | # sendEmail Source: https://docs.modelence.com/api-reference/@modelence/resend/functions/sendEmail [API Reference](/api-reference/@modelence/resend/functions/../../../index) / [@modelence/resend](/api-reference/@modelence/resend/functions/../index) / sendEmail > **sendEmail**(`payload`): `Promise`\<`void`> Defined in: [index.ts:57](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L57) Sends an email via Resend. ## Example ```ts theme={null} import { sendEmail } from '@modelence/aws-ses'; sendEmail({ from: 'test@example.com', to: 'test@example.com', subject: 'Test Email', html: '

Hello World

' }) ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `payload` | [`EmailPayload`](/api-reference/@modelence/resend/functions/../type-aliases/EmailPayload) | The email payload object. | ## Returns `Promise`\<`void`> # @modelence/resend Source: https://docs.modelence.com/api-reference/@modelence/resend/index [API Reference](/api-reference/@modelence/resend/../../index) / @modelence/resend ## Type Aliases * [EmailAttachment](/api-reference/@modelence/resend/type-aliases/EmailAttachment) * [EmailPayload](/api-reference/@modelence/resend/type-aliases/EmailPayload) ## Variables * [default](/api-reference/@modelence/resend/variables/default) ## Functions * [sendEmail](/api-reference/@modelence/resend/functions/sendEmail) # EmailAttachment Source: https://docs.modelence.com/api-reference/@modelence/resend/type-aliases/EmailAttachment [API Reference](/api-reference/@modelence/resend/type-aliases/../../../index) / [@modelence/resend](/api-reference/@modelence/resend/type-aliases/../index) / EmailAttachment > **EmailAttachment** = `object` Defined in: [index.ts:6](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L6) ## Properties | Property | Type | Defined in | | - | - | - | | `content` | `Buffer` \| `string` | [index.ts:8](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L8) | | `contentType` | `string` | [index.ts:9](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L9) | | `filename` | `string` | [index.ts:7](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L7) | # EmailPayload Source: https://docs.modelence.com/api-reference/@modelence/resend/type-aliases/EmailPayload [API Reference](/api-reference/@modelence/resend/type-aliases/../../../index) / [@modelence/resend](/api-reference/@modelence/resend/type-aliases/../index) / EmailPayload > **EmailPayload** = `object` & \{ `html`: `string`; } | \{ `text`: `string`; } Defined in: [index.ts:12](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L12) ## Type declaration | Name | Type | Defined in | | - | - | - | | `attachments?` | [`EmailAttachment`](/api-reference/@modelence/resend/type-aliases/EmailAttachment)\[] | [index.ts:22](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L22) | | `bcc?` | `string` \| `string`\[] | [index.ts:19](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L19) | | `cc?` | `string` \| `string`\[] | [index.ts:18](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L18) | | `from` | `string` | [index.ts:13](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L13) | | `headers?` | `Record`\<`string`, `string`> | [index.ts:21](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L21) | | `html?` | `string` | [index.ts:16](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L16) | | `replyTo?` | `string` \| `string`\[] | [index.ts:20](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L20) | | `subject` | `string` | [index.ts:15](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L15) | | `text?` | `string` | [index.ts:17](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L17) | | `to` | `string` \| `string`\[] | [index.ts:14](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L14) | # default Source: https://docs.modelence.com/api-reference/@modelence/resend/variables/default [API Reference](/api-reference/@modelence/resend/variables/../../../index) / [@modelence/resend](/api-reference/@modelence/resend/variables/../index) / default > **default**: `EmailProvider` Defined in: [index.ts:99](https://github.com/modelence/modelence/blob/main/packages/resend/src/index.ts#L99) # sendEmail Source: https://docs.modelence.com/api-reference/@modelence/smtp/functions/sendEmail [API Reference](/api-reference/@modelence/smtp/functions/../../../index) / [@modelence/smtp](/api-reference/@modelence/smtp/functions/../index) / sendEmail > **sendEmail**(`payload`): `Promise`\<`void`> Defined in: [index.ts:78](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L78) Sends an email via Resend. ## Example ```ts theme={null} import { sendEmail } from '@modelence/aws-ses'; sendEmail({ from: 'test@example.com', to: 'test@example.com', subject: 'Test Email', html: '

Hello World

' }) ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `payload` | [`EmailPayload`](/api-reference/@modelence/smtp/functions/../type-aliases/EmailPayload) | The email payload object. | ## Returns `Promise`\<`void`> # @modelence/smtp Source: https://docs.modelence.com/api-reference/@modelence/smtp/index [API Reference](/api-reference/@modelence/smtp/../../index) / @modelence/smtp ## Type Aliases * [EmailAttachment](/api-reference/@modelence/smtp/type-aliases/EmailAttachment) * [EmailPayload](/api-reference/@modelence/smtp/type-aliases/EmailPayload) ## Variables * [default](/api-reference/@modelence/smtp/variables/default) ## Functions * [sendEmail](/api-reference/@modelence/smtp/functions/sendEmail) # EmailAttachment Source: https://docs.modelence.com/api-reference/@modelence/smtp/type-aliases/EmailAttachment [API Reference](/api-reference/@modelence/smtp/type-aliases/../../../index) / [@modelence/smtp](/api-reference/@modelence/smtp/type-aliases/../index) / EmailAttachment > **EmailAttachment** = `object` Defined in: [index.ts:7](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L7) ## Properties | Property | Type | Defined in | | - | - | - | | `content` | `Buffer` \| `string` | [index.ts:9](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L9) | | `contentType` | `string` | [index.ts:10](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L10) | | `filename` | `string` | [index.ts:8](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L8) | # EmailPayload Source: https://docs.modelence.com/api-reference/@modelence/smtp/type-aliases/EmailPayload [API Reference](/api-reference/@modelence/smtp/type-aliases/../../../index) / [@modelence/smtp](/api-reference/@modelence/smtp/type-aliases/../index) / EmailPayload > **EmailPayload** = `object` & \{ `html`: `string`; } | \{ `text`: `string`; } Defined in: [index.ts:13](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L13) ## Type declaration | Name | Type | Defined in | | - | - | - | | `attachments?` | [`EmailAttachment`](/api-reference/@modelence/smtp/type-aliases/EmailAttachment)\[] | [index.ts:23](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L23) | | `bcc?` | `string` \| `string`\[] | [index.ts:20](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L20) | | `cc?` | `string` \| `string`\[] | [index.ts:19](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L19) | | `from` | `string` | [index.ts:14](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L14) | | `headers?` | `Record`\<`string`, `string`> | [index.ts:22](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L22) | | `html?` | `string` | [index.ts:17](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L17) | | `replyTo?` | `string` \| `string`\[] | [index.ts:21](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L21) | | `subject` | `string` | [index.ts:16](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L16) | | `text?` | `string` | [index.ts:18](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L18) | | `to` | `string` \| `string`\[] | [index.ts:15](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L15) | # default Source: https://docs.modelence.com/api-reference/@modelence/smtp/variables/default [API Reference](/api-reference/@modelence/smtp/variables/../../../index) / [@modelence/smtp](/api-reference/@modelence/smtp/variables/../index) / default > **default**: `EmailProvider` Defined in: [index.ts:108](https://github.com/modelence/modelence/blob/main/packages/smtp/src/index.ts#L108) # ClientChannel Source: https://docs.modelence.com/api-reference/modelence/client/classes/ClientChannel [API Reference](/api-reference/modelence/client/classes/../../../index) / [modelence](/api-reference/modelence/client/classes/../../index) / [client](/api-reference/modelence/client/classes/../index) / ClientChannel Defined in: [packages/modelence/src/websocket/clientChannel.ts:3](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/clientChannel.ts#L3) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Constructors ### Constructor > **new ClientChannel**\<`T`>(`category`, `onMessage`): `ClientChannel`\<`T`> Defined in: [packages/modelence/src/websocket/clientChannel.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/clientChannel.ts#L7) #### Parameters | Parameter | Type | | - | - | | `category` | `string` | | `onMessage` | (`data`) => `void` | #### Returns `ClientChannel`\<`T`> ## Properties | Property | Modifier | Type | Defined in | | - | - | - | - | | `category` | `readonly` | `string` | [packages/modelence/src/websocket/clientChannel.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/clientChannel.ts#L4) | ## Methods ### init() > **init**(): `void` Defined in: [packages/modelence/src/websocket/clientChannel.ts:12](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/clientChannel.ts#L12) #### Returns `void` *** ### joinChannel() > **joinChannel**(`id`): `void` Defined in: [packages/modelence/src/websocket/clientChannel.ts:19](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/clientChannel.ts#L19) #### Parameters | Parameter | Type | | - | - | | `id` | `string` | #### Returns `void` *** ### leaveChannel() > **leaveChannel**(`id`): `void` Defined in: [packages/modelence/src/websocket/clientChannel.ts:26](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/clientChannel.ts#L26) #### Parameters | Parameter | Type | | - | - | | `id` | `string` | #### Returns `void` # MethodError Source: https://docs.modelence.com/api-reference/modelence/client/classes/MethodError [API Reference](/api-reference/modelence/client/classes/../../../index) / [modelence](/api-reference/modelence/client/classes/../../index) / [client](/api-reference/modelence/client/classes/../index) / MethodError Defined in: [packages/modelence/src/client/method.ts:15](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L15) ## Extends * `Error` ## Constructors ### Constructor > **new MethodError**(`message`, `status`, `code?`): `MethodError` Defined in: [packages/modelence/src/client/method.ts:25](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L25) #### Parameters | Parameter | Type | | - | - | | `message` | `string` | | `status` | `number` | | `code?` | `string` | #### Returns `MethodError` #### Overrides `Error.constructor` ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `code?` | `string` | Machine-readable error code set by the server (when available), so callers can branch on the error kind without matching the human-readable message. For example, a login attempt with an unverified email yields `code === 'EMAIL_NOT_VERIFIED'`. | [packages/modelence/src/client/method.ts:23](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L23) | | `status` | `number` | - | [packages/modelence/src/client/method.ts:16](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L16) | # ModelenceQueryClient Source: https://docs.modelence.com/api-reference/modelence/client/classes/ModelenceQueryClient [API Reference](/api-reference/modelence/client/classes/../../../index) / [modelence](/api-reference/modelence/client/classes/../../index) / [client](/api-reference/modelence/client/classes/../index) / ModelenceQueryClient Defined in: [packages/modelence/src/client/query.ts:91](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L91) ## Deprecated Use `connectModelenceQueryClient(queryClient)` instead. ## Constructors ### Constructor > **new ModelenceQueryClient**(): `ModelenceQueryClient` #### Returns `ModelenceQueryClient` ## Methods ### ~~connect()~~ > **connect**(`queryClient`): `void` Defined in: [packages/modelence/src/client/query.ts:92](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L92) #### Parameters | Parameter | Type | | - | - | | `queryClient` | `QueryClient` | #### Returns `void` # ModelenceQueryProvider Source: https://docs.modelence.com/api-reference/modelence/client/functions/ModelenceQueryProvider [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / ModelenceQueryProvider > **ModelenceQueryProvider**(`__namedParameters`): `Element` Defined in: [packages/modelence/src/client/queryProvider.tsx:70](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/queryProvider.tsx#L70) ## Parameters | Parameter | Type | | - | - | | `__namedParameters` | `ModelenceQueryProviderProps` | ## Returns `Element` # callMethod Source: https://docs.modelence.com/api-reference/modelence/client/functions/callMethod [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / callMethod > **callMethod**\<`T`>(`methodName`, `args?`, `options?`): `Promise`\<`T`> Defined in: [packages/modelence/src/client/method.ts:103](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L103) Calls a server-side method (query or mutation) defined on a Modelence module. Both `args` and `options` are optional. Use the type parameter `T` to type the return value. ## Example ```typescript theme={null} import { callMethod } from 'modelence/client'; // No arguments const todos = await callMethod('todo.getAll'); // With arguments const todo = await callMethod('todo.getOne', { id: '123' }); // With a custom error handler const created = await callMethod( 'todo.create', { title: 'Buy groceries' }, { errorHandler: (error, methodName) => console.error(methodName, error) } ); ``` ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Parameters | Parameter | Type | Description | | - | - | - | | `methodName` | `string` | Fully qualified method name, e.g. `'todo.getAll'`. | | `args?` | [`MethodArgs`](/api-reference/modelence/client/functions/../type-aliases/MethodArgs) | Arguments passed to the server-side method. Defaults to `{}`. | | `options?` | [`CallMethodOptions`](/api-reference/modelence/client/functions/../type-aliases/CallMethodOptions) | Call-site options such as a custom [CallMethodOptions.errorHandler](../type-aliases/CallMethodOptions#errorhandler). Defaults to `{}`. | ## Returns `Promise`\<`T`> A promise that resolves to the method's return value. # cancelOAuthPopup Source: https://docs.modelence.com/api-reference/modelence/client/functions/cancelOAuthPopup [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / cancelOAuthPopup > **cancelOAuthPopup**(): `void` Defined in: [packages/modelence/src/auth/client/index.ts:545](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L545) Abandons a popup sign-in this page was waiting on. ## Returns `void` # configureClient Source: https://docs.modelence.com/api-reference/modelence/client/functions/configureClient [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / configureClient > **configureClient**(`userConfig`): `void` Defined in: [packages/modelence/src/client/clientConfig.ts:66](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L66) Configure the Modelence client for non-browser environments like React Native. When configured, the client uses the provided functions for auth-token storage, client-info collection, and URL resolution instead of the default browser APIs (localStorage, window\.screen, relative URLs). ## Example ```ts theme={null} import { configureClient } from 'modelence/client'; import { Linking } from 'react-native'; let authToken: string | undefined; configureClient({ baseUrl: 'https://myapp.com', getAuthToken: () => authToken, setAuthToken: (token) => { authToken = token ?? undefined; }, getClientInfo: () => ({ screenWidth: Dimensions.get('screen').width, screenHeight: Dimensions.get('screen').height, windowWidth: Dimensions.get('window').width, windowHeight: Dimensions.get('window').height, pixelRatio: PixelRatio.get(), orientation: null, }), openUrl: (url) => Linking.openURL(url), }); ``` ## Parameters | Parameter | Type | | - | - | | `userConfig` | [`ClientConfig`](/api-reference/modelence/client/functions/../interfaces/ClientConfig) | ## Returns `void` # connectModelenceQueryClient Source: https://docs.modelence.com/api-reference/modelence/client/functions/connectModelenceQueryClient [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / connectModelenceQueryClient > **connectModelenceQueryClient**(`queryClient`): `void` Defined in: [packages/modelence/src/client/query.ts:32](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L32) Connects a `QueryClient` to Modelence's live-query layer. Auto-called by ``; only call manually if you mount your own ``. Note: WebSocket setup is deferred until the first `modelenceLiveQuery` call, so apps that only use `modelenceQuery`/`modelenceMutation` never open a socket. ## Parameters | Parameter | Type | | - | - | | `queryClient` | `QueryClient` | ## Returns `void` # createClientModule Source: https://docs.modelence.com/api-reference/modelence/client/functions/createClientModule [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / createClientModule > **createClientModule**\<`TModule`>(`moduleName`): `object` Defined in: [packages/modelence/src/client/module.ts:88](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L88) Creates a typed client accessor for a module's public configs, queries, and mutations. Use `import type` to reference the module so no server code is bundled on the client. Arg and return types for queries and mutations are inferred automatically from the server-side handler signatures. ## Example ```ts theme={null} // src/client/payments.ts import type paymentsModule from '../server/payments'; import { createClientModule } from 'modelence/client'; export const payments = createClientModule('payments'); ``` ```ts theme={null} // src/components/Checkout.tsx import { useQuery, useMutation } from '@tanstack/react-query'; import { payments } from '../client/payments'; // Typed config — public keys only, private and secret keys excluded: const currency = payments.getConfig('currency'); // string | undefined // Typed query — pass directly to useQuery: const { data: products } = useQuery(payments.query('getProducts', { page: 1 })); // Typed mutation — pass directly to useMutation: const { mutate: charge } = useMutation(payments.mutation('charge')); charge({ amount: 100 }); // args typed from handler signature ``` ## Type Parameters | Type Parameter | | - | | `TModule` *extends* `AnyModule` | ## Parameters | Parameter | Type | Description | | - | - | - | | `moduleName` | `string` | The module's name as passed to `new Module(name, ...)`. | ## Returns | Name | Type | Description | Defined in | | - | - | - | - | | `getConfig()` | (`key`) => `undefined` \| `PublicKeyOf`\<`TModule`\[`"configSchema"`]>\[`K`] | - | [packages/modelence/src/client/module.ts:90](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L90) | | `infiniteQuery()` | (`name`, `getArgs`) => `object` | Returns options for `useInfiniteQuery`. The `getArgs` callback receives the current `pageParam` and returns the args to pass to the query handler. Spread the result into `useInfiniteQuery` alongside `getNextPageParam`. Annotate the `pageParam` type in the callback so TypeScript can infer the page param type — no manual generic needed on `useInfiniteQuery`. | [packages/modelence/src/client/module.ts:134](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L134) | | `mutation()` | (`name`) => `object` | - | [packages/modelence/src/client/module.ts:114](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L114) | | `query()` | (`name`, ...`rest`) => `object` | - | [packages/modelence/src/client/module.ts:97](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L97) | # createQueryKey Source: https://docs.modelence.com/api-reference/modelence/client/functions/createQueryKey [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / createQueryKey > **createQueryKey**\<`T`, `U`>(`methodName`, `args`): [`ModelenceQueryKey`](/api-reference/modelence/client/functions/../type-aliases/ModelenceQueryKey)\<`T`, `U`> Defined in: [packages/modelence/src/client/query.ts:212](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L212) Builds a query key matching `modelenceQuery(...)` for cache operations. ## Type Parameters | Type Parameter | Default type | | - | - | | `T` *extends* `string` | - | | `U` *extends* `Args` | `Args` | ## Parameters | Parameter | Type | | - | - | | `methodName` | `T` | | `args` | `U` | ## Returns [`ModelenceQueryKey`](/api-reference/modelence/client/functions/../type-aliases/ModelenceQueryKey)\<`T`, `U`> # disconnectModelenceQueryClient Source: https://docs.modelence.com/api-reference/modelence/client/functions/disconnectModelenceQueryClient [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / disconnectModelenceQueryClient > **disconnectModelenceQueryClient**(): `void` Defined in: [packages/modelence/src/client/query.ts:69](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L69) ## Returns `void` # getConfig Source: https://docs.modelence.com/api-reference/modelence/client/functions/getConfig [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / getConfig > **getConfig**(`key`): `undefined` | `string` | `number` | `boolean` Defined in: [packages/modelence/src/config/client.ts:19](https://github.com/modelence/modelence/blob/main/packages/modelence/src/config/client.ts#L19) ## Parameters | Parameter | Type | | - | - | | `key` | `string` | ## Returns `undefined` | `string` | `number` | `boolean` ## Sidebar Title getConfig (client) # getLocalStorageSession Source: https://docs.modelence.com/api-reference/modelence/client/functions/getLocalStorageSession [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / getLocalStorageSession > **getLocalStorageSession**(): `any` Defined in: [packages/modelence/src/client/localStorage.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/localStorage.ts#L7) ## Returns `any` # getWebsocketClientProvider Source: https://docs.modelence.com/api-reference/modelence/client/functions/getWebsocketClientProvider [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / getWebsocketClientProvider > **getWebsocketClientProvider**(): `null` | [`WebsocketClientProvider`](/api-reference/modelence/client/functions/../../index/interfaces/WebsocketClientProvider) Defined in: [packages/modelence/src/websocket/client.ts:13](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/client.ts#L13) ## Returns `null` | [`WebsocketClientProvider`](/api-reference/modelence/client/functions/../../index/interfaces/WebsocketClientProvider) # linkOAuthProvider Source: https://docs.modelence.com/api-reference/modelence/client/functions/linkOAuthProvider [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / linkOAuthProvider > **linkOAuthProvider**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:571](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L571) Link an OAuth provider to the currently signed-in user's account. Redirects the browser to the OAuth provider's authorization page. The provider will redirect back and the account will be linked. Without `redirectUri` this navigates the current context and authenticates with an httpOnly cookie, so it only works where the navigation stays in the same cookie jar — a browser, or a webview that navigates in place. Clients whose `openUrl` opens an external browser (Electron, Capacitor) must pass a `redirectUri`: that flow carries a single-use nonce in the URL and does not depend on cookies. ## Example ```ts theme={null} linkOAuthProvider({ provider: 'google' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `provider`: `"google"` \| `"github"`; `redirectUri?`: `string`; } | - | | `options.provider` | `"google"` \| `"github"` | The OAuth provider to link ('google' or 'github'). | | `options.redirectUri?` | `string` | Deep link to return to once linking completes. Required for React Native and any client that opens URLs externally; must be listed in the server's `auth.mobile.redirectUrls`. Without it the flow ends wherever the navigation lands rather than back in the app. | ## Returns `Promise`\<`void`> # loginWithMagicLink Source: https://docs.modelence.com/api-reference/modelence/client/functions/loginWithMagicLink [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / loginWithMagicLink > **loginWithMagicLink**(): `Promise`\<`null` | `User`> Defined in: [packages/modelence/src/auth/client/index.ts:237](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L237) Complete a magic link sign-in. Call this from the page the magic link landing route redirects to. The token is exchanged server-side via an httpOnly cookie, so no arguments are needed. Signs the user in — creating the account first when the email is not registered yet and the server enables `auth.magicLink.allowSignup` — and returns the logged-in user. ## Example ```ts theme={null} const user = await loginWithMagicLink(); ``` ## Returns `Promise`\<`null` | `User`> # loginWithOAuth Source: https://docs.modelence.com/api-reference/modelence/client/functions/loginWithOAuth [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / loginWithOAuth > **loginWithOAuth**(`options`): `Promise`\<`null` | `User`> Defined in: [packages/modelence/src/auth/client/index.ts:500](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L500) Complete a native OAuth sign-in with the code from the deep link. Exchanges the single-use code that [signInWithOAuth](/api-reference/modelence/client/functions/signInWithOAuth) delivered to your app's deep link for a session, stores the auth token, and returns the signed-in user. Codes are valid for one minute and can only be redeemed once. Pairs with `signInWithOAuth({ provider, redirectUri })` — the flow that hands a code back to your app. It works on native and under Expo Web, where the verifier is kept in `sessionStorage` so it survives the navigation to the provider. When this page is an OAuth popup opened by a page that is still listening — the embedded-iframe case, where `openUrl` returned the window from `window.open` — the code is handed to that opening page instead, and the sign-in completes *there*, in the context the app actually runs in. This call then resolves to `null`: there is no user to return here, and this page is closed for you. A plain web app that calls `signInWithOAuth({ provider })` with no `redirectUri` is signed in by a session cookie and never needs this. The verifier minted by `signInWithOAuth` is replayed by whichever context redeems the code, which is what makes a code usable only by the client that started the flow. Calling this without a preceding `signInWithOAuth` — as a crafted deep link would — fails before the code is ever sent. ## Example ```ts theme={null} const user = await loginWithOAuth({ code }); if (user) { // Signed in here. In an embedded popup, user is null and the opening // page has completed the sign-in instead. } ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `code`: `string`; } | - | | `options.code` | `string` | The `code` query parameter from the deep link. | ## Returns `Promise`\<`null` | `User`> # loginWithOneTimeCode Source: https://docs.modelence.com/api-reference/modelence/client/functions/loginWithOneTimeCode [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / loginWithOneTimeCode > **loginWithOneTimeCode**(`options`): `Promise`\<`null` | `User`> Defined in: [packages/modelence/src/auth/client/index.ts:260](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L260) Complete a magic link sign-in by typing the one-time code from the email. Alternative to `loginWithMagicLink()` for contexts where clicking the link can't reach the app — native apps without deep links, or when the email is read on a different device. Signs the user in — creating the account first when the email is not registered yet and the server enables `auth.magicLink.allowSignup` — and returns the logged-in user. ## Example ```ts theme={null} const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `code`: `string`; `email`: `string`; } | - | | `options.code` | `string` | The one-time code from the email. | | `options.email` | `string` | The email the magic link was sent to. | ## Returns `Promise`\<`null` | `User`> # loginWithPassword Source: https://docs.modelence.com/api-reference/modelence/client/functions/loginWithPassword [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / loginWithPassword > **loginWithPassword**(`options`): `Promise`\<`null` | `User`> Defined in: [packages/modelence/src/auth/client/index.ts:106](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L106) Login a user with an email and password. ## Example ```ts theme={null} await loginWithPassword({ email: 'test@example.com', password: '12345678' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `email`: `string`; `password`: `string`; } | - | | `options.email` | `string` | The email of the user. | | `options.password` | `string` | The password of the user. | ## Returns `Promise`\<`null` | `User`> # logout Source: https://docs.modelence.com/api-reference/modelence/client/functions/logout [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / logout > **logout**(): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:181](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L181) Logout the current user. ## Returns `Promise`\<`void`> # modelenceLiveQuery Source: https://docs.modelence.com/api-reference/modelence/client/functions/modelenceLiveQuery [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / modelenceLiveQuery > **modelenceLiveQuery**\<`T`>(`methodName`, `args`): `object` Defined in: [packages/modelence/src/client/query.ts:115](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L115) Live query — data updates in real time as the underlying collection changes. Requires a `QueryClient` connected via `` or `connectModelenceQueryClient(...)`. ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Parameters | Parameter | Type | | - | - | | `methodName` | `string` | | `args` | `Args` | ## Returns `object` | Name | Type | Default value | Defined in | | - | - | - | - | | `gcTime` | `number` | `0` | [packages/modelence/src/client/query.ts:198](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L198) | | `queryFn()` | () => `Promise`\<`T`> | - | [packages/modelence/src/client/query.ts:121](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L121) | | `queryKey` | readonly \[`"live"`, `string`, `Args`] | - | [packages/modelence/src/client/query.ts:120](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L120) | | `refetchOnMount` | `boolean` | `false` | [packages/modelence/src/client/query.ts:196](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L196) | | `refetchOnReconnect` | `boolean` | `false` | [packages/modelence/src/client/query.ts:197](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L197) | | `refetchOnWindowFocus` | `boolean` | `false` | [packages/modelence/src/client/query.ts:195](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L195) | | `staleTime` | `number` | `Infinity` | [packages/modelence/src/client/query.ts:194](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L194) | # modelenceMutation Source: https://docs.modelence.com/api-reference/modelence/client/functions/modelenceMutation [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / modelenceMutation > **modelenceMutation**\<`T`>(`methodName`, `defaultArgs`): `object` Defined in: [packages/modelence/src/client/query.ts:202](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L202) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Parameters | Parameter | Type | | - | - | | `methodName` | `string` | | `defaultArgs` | `Args` | ## Returns `object` | Name | Type | Defined in | | - | - | - | | `mutationFn()` | (`variables`) => `Promise`\<`T`> | [packages/modelence/src/client/query.ts:204](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L204) | # modelenceQuery Source: https://docs.modelence.com/api-reference/modelence/client/functions/modelenceQuery [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / modelenceQuery > **modelenceQuery**\<`T`>(`methodName`, `args`): `object` Defined in: [packages/modelence/src/client/query.ts:103](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L103) ## Example ```tsx theme={null} const { data } = useQuery(modelenceQuery('todo.getAll')); ``` ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Parameters | Parameter | Type | | - | - | | `methodName` | `string` | | `args` | `Args` | ## Returns `object` | Name | Type | Defined in | | - | - | - | | `queryFn()` | () => `Promise`\<`T`> | [packages/modelence/src/client/query.ts:106](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L106) | | `queryKey` | (`string` \| `Args`)\[] | [packages/modelence/src/client/query.ts:105](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L105) | # parseDeepLinkParams Source: https://docs.modelence.com/api-reference/modelence/client/functions/parseDeepLinkParams [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / parseDeepLinkParams > **parseDeepLinkParams**(`url`): `Record`\<`string`, `string`> Defined in: [packages/modelence/src/auth/client/deepLink.ts:18](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/deepLink.ts#L18) Reads query parameters out of a deep link such as `myapp://auth?code=abc`. Only the query component is considered — everything from the first `?` up to an optional `#` fragment. Values are percent-decoded, with `+` treated as a space to match `application/x-www-form-urlencoded`, which is how the server's `URL.searchParams.set` encodes them. ## Parameters | Parameter | Type | | - | - | | `url` | `string` | ## Returns `Record`\<`string`, `string`> # renderApp Source: https://docs.modelence.com/api-reference/modelence/client/functions/renderApp [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / renderApp > **renderApp**(`options`): `void` Defined in: [packages/modelence/src/client/renderApp.tsx:82](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/renderApp.tsx#L82) ## Parameters | Parameter | Type | | - | - | | `options` | `RenderAppOptions` | ## Returns `void` # resendEmailVerification Source: https://docs.modelence.com/api-reference/modelence/client/functions/resendEmailVerification [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / resendEmailVerification > **resendEmailVerification**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:172](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L172) Resend the verification email for a given email address. The email is only sent if the address is registered and not yet verified. A generic response is always returned to avoid leaking account information. ## Example ```ts theme={null} await resendEmailVerification({ email: 'user@example.com' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `email`: `string`; } | - | | `options.email` | `string` | The email address to resend verification to. | ## Returns `Promise`\<`void`> # resetPassword Source: https://docs.modelence.com/api-reference/modelence/client/functions/resetPassword [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / resetPassword > **resetPassword**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:279](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L279) Reset password. The token is normally exchanged server-side via an httpOnly cookie, so the client only submits the new password. Pass `token` only for legacy flows that still carry it client-side (deprecated). ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `password`: `string`; `token?`: `string`; } | - | | `options.password` | `string` | The new password. | | `options.token?` | `string` | Reset token (optional; read from the httpOnly cookie when omitted). | ## Returns `Promise`\<`void`> # resumeOAuthPopup Source: https://docs.modelence.com/api-reference/modelence/client/functions/resumeOAuthPopup [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / resumeOAuthPopup > **resumeOAuthPopup**(`options`): `boolean` Defined in: [packages/modelence/src/auth/client/index.ts:538](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L538) Resume a popup sign-in after the opening page reloaded mid-flow. An embedded preview that refreshes while the popup is at the provider loses the in-memory listener that would receive the code. The verifier survives in `sessionStorage`, so pass the popup window back in on load to keep the flow alive. ## Example ```ts theme={null} const popup = window.open('', 'modelence-oauth'); if (popup) resumeOAuthPopup({ popup }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `popup`: `unknown`; } | - | | `options.popup` | `unknown` | The popup window that is still completing the flow. | ## Returns `boolean` Whether a sign-in was pending and the handoff was re-armed. # sendMagicLink Source: https://docs.modelence.com/api-reference/modelence/client/functions/sendMagicLink [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / sendMagicLink > **sendMagicLink**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:216](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L216) Send a magic sign-in link to the given email address. Clicking the emailed link signs the user in. When the server enables `auth.magicLink.allowSignup`, this also works for new users — the account is created when the link is used; otherwise unknown emails receive no email. A generic response is always returned to avoid leaking account information. ## Example ```ts theme={null} await sendMagicLink({ email: 'user@example.com' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `email`: `string`; } | - | | `options.email` | `string` | The email address to send the magic link to. | ## Returns `Promise`\<`void`> # sendResetPasswordToken Source: https://docs.modelence.com/api-reference/modelence/client/functions/sendResetPasswordToken [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / sendResetPasswordToken > **sendResetPasswordToken**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:195](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L195) Send reset password token. ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `email`: `string`; } | - | | `options.email` | `string` | The email of the user. | ## Returns `Promise`\<`void`> # setWebsocketClientProvider Source: https://docs.modelence.com/api-reference/modelence/client/functions/setWebsocketClientProvider [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / setWebsocketClientProvider > **setWebsocketClientProvider**(`provider`): `void` Defined in: [packages/modelence/src/websocket/client.ts:9](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/client.ts#L9) ## Parameters | Parameter | Type | | - | - | | `provider` | `null` \| [`WebsocketClientProvider`](/api-reference/modelence/client/functions/../../index/interfaces/WebsocketClientProvider) | ## Returns `void` # signInWithOAuth Source: https://docs.modelence.com/api-reference/modelence/client/functions/signInWithOAuth [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / signInWithOAuth > **signInWithOAuth**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:323](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L323) Start an OAuth sign-in. On the web this navigates to the provider and the flow finishes on its own — the session cookie is set and the browser lands back on your site. Pass `redirectUri` to run the native flow: the device browser opens the provider, and when the flow completes Modelence redirects back to that deep link with a single-use `code` query parameter. Hand that code to [loginWithOAuth](/api-reference/modelence/client/functions/loginWithOAuth) to finish signing in. The redirect target must be listed in the server's `auth.mobile.redirectUrls`, otherwise the request is rejected before the provider is ever reached. The native flow additionally binds the sign-in to this device: a verifier is held in memory here and replayed by `loginWithOAuth`, so a `code` delivered to the app from outside this flow cannot be redeemed. ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `provider`: `"google"` \| `"github"`; `redirectUri?`: `string`; } | - | | `options.provider` | `"google"` \| `"github"` | The OAuth provider to sign in with ('google' or 'github'). | | `options.redirectUri?` | `string` | Deep link to return to. Required on React Native. | ## Returns `Promise`\<`void`> ## Examples ```ts theme={null} await signInWithOAuth({ provider: 'google' }); ``` ```ts theme={null} import { parseDeepLinkParams } from 'modelence/client'; await signInWithOAuth({ provider: 'google', redirectUri: 'myapp://auth' }); Linking.addEventListener('url', async ({ url }) => { const { code } = parseDeepLinkParams(url); if (code) await loginWithOAuth({ code }); }); ``` # signupWithPassword Source: https://docs.modelence.com/api-reference/modelence/client/functions/signupWithPassword [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / signupWithPassword > **signupWithPassword**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:77](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L77) Sign up a new user with an email and password. ## Example ```ts theme={null} await signupWithPassword({ email: 'test@example.com', password: '12345678' }); await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `avatarUrl?`: `string`; `email`: `string`; `firstName?`: `string`; `handle?`: `string`; `lastName?`: `string`; `password`: `string`; } | - | | `options.avatarUrl?` | `string` | Optional avatar URL. | | `options.email` | `string` | The email of the user. | | `options.firstName?` | `string` | Optional first name. | | `options.handle?` | `string` | Optional custom handle. If omitted, one is derived from the email. | | `options.lastName?` | `string` | Optional last name. | | `options.password` | `string` | The password of the user. | ## Returns `Promise`\<`void`> # startWebsockets Source: https://docs.modelence.com/api-reference/modelence/client/functions/startWebsockets [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / startWebsockets > **startWebsockets**(`props?`): `void` Defined in: [packages/modelence/src/websocket/client.ts:17](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/client.ts#L17) ## Parameters | Parameter | Type | | - | - | | `props?` | \{ `channels?`: [`ClientChannel`](/api-reference/modelence/client/functions/../classes/ClientChannel)\<`unknown`>\[]; `provider?`: [`WebsocketClientProvider`](/api-reference/modelence/client/functions/../../index/interfaces/WebsocketClientProvider); } | | `props.channels?` | [`ClientChannel`](/api-reference/modelence/client/functions/../classes/ClientChannel)\<`unknown`>\[] | | `props.provider?` | [`WebsocketClientProvider`](/api-reference/modelence/client/functions/../../index/interfaces/WebsocketClientProvider) | ## Returns `void` # subscribeLiveQuery Source: https://docs.modelence.com/api-reference/modelence/client/functions/subscribeLiveQuery [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / subscribeLiveQuery > **subscribeLiveQuery**\<`T`>(`method`, `args`, `onData`, `onError?`): () => `void` Defined in: [packages/modelence/src/websocket/socketio/client.ts:126](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/socketio/client.ts#L126) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Parameters | Parameter | Type | | - | - | | `method` | `string` | | `args` | `Record`\<`string`, `unknown`> | | `onData` | (`data`) => `void` | | `onError?` | (`error`) => `void` | ## Returns > (): `void` ### Returns `void` # unlinkOAuthProvider Source: https://docs.modelence.com/api-reference/modelence/client/functions/unlinkOAuthProvider [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / unlinkOAuthProvider > **unlinkOAuthProvider**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:638](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L638) Unlink an OAuth provider from the currently signed-in user's account. ## Example ```ts theme={null} await unlinkOAuthProvider({ provider: 'github' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `provider`: `"google"` \| `"github"`; } | - | | `options.provider` | `"google"` \| `"github"` | The OAuth provider to unlink ('google' or 'github'). | ## Returns `Promise`\<`void`> # updateProfile Source: https://docs.modelence.com/api-reference/modelence/client/functions/updateProfile [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / updateProfile > **updateProfile**(`options`): `Promise`\<`null` | `User`> Defined in: [packages/modelence/src/auth/client/index.ts:130](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L130) Update the current user's profile. ## Example ```ts theme={null} await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `avatarUrl?`: `string`; `firstName?`: `string`; `handle?`: `string`; `lastName?`: `string`; } | - | | `options.avatarUrl?` | `string` | The avatar URL of the user. | | `options.firstName?` | `string` | The first name of the user. | | `options.handle?` | `string` | The handle of the user. | | `options.lastName?` | `string` | The last name of the user. | ## Returns `Promise`\<`null` | `User`> # useSession Source: https://docs.modelence.com/api-reference/modelence/client/functions/useSession [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / useSession > **useSession**(): `object` Defined in: [packages/modelence/src/client/session.ts:262](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/session.ts#L262) `useSession` is a hook that returns the current user, and in the future will also return other details about the current session. ## Example ```ts theme={null} import { useSession } from 'modelence/client'; function MyComponent() { const { user } = useSession(); return
{user?.handle}
; } ``` ## Returns `object` | Name | Type | Defined in | | - | - | - | | `user` | `null` \| `User` | [packages/modelence/src/client/session.ts:264](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/session.ts#L264) | # verifyEmail Source: https://docs.modelence.com/api-reference/modelence/client/functions/verifyEmail [API Reference](/api-reference/modelence/client/functions/../../../index) / [modelence](/api-reference/modelence/client/functions/../../index) / [client](/api-reference/modelence/client/functions/../index) / verifyEmail > **verifyEmail**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/client/index.ts:156](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L156) Verify user's email with a verification token. ## Example ```ts theme={null} await verifyEmail({ token: 'verification-token' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `token`: `string`; } | - | | `options.token` | `string` | The email verification token. | ## Returns `Promise`\<`void`> # client Source: https://docs.modelence.com/api-reference/modelence/client/index [API Reference](/api-reference/modelence/client/../../index) / [modelence](/api-reference/modelence/client/../index) / client ## Classes * [ClientChannel](/api-reference/modelence/client/classes/ClientChannel) * [MethodError](/api-reference/modelence/client/classes/MethodError) * [~~ModelenceQueryClient~~](/api-reference/modelence/client/classes/ModelenceQueryClient) ## Interfaces * [ClientConfig](/api-reference/modelence/client/interfaces/ClientConfig) ## Type Aliases * [CallMethodOptions](/api-reference/modelence/client/type-aliases/CallMethodOptions) * [MethodArgs](/api-reference/modelence/client/type-aliases/MethodArgs) * [ModelenceQueryKey](/api-reference/modelence/client/type-aliases/ModelenceQueryKey) * [UserInfo](/api-reference/modelence/client/type-aliases/UserInfo) ## Variables * [AppProvider](/api-reference/modelence/client/variables/AppProvider) * [systemConfig](/api-reference/modelence/client/variables/systemConfig) ## Functions * [callMethod](/api-reference/modelence/client/functions/callMethod) * [cancelOAuthPopup](/api-reference/modelence/client/functions/cancelOAuthPopup) * [configureClient](/api-reference/modelence/client/functions/configureClient) * [connectModelenceQueryClient](/api-reference/modelence/client/functions/connectModelenceQueryClient) * [createClientModule](/api-reference/modelence/client/functions/createClientModule) * [createQueryKey](/api-reference/modelence/client/functions/createQueryKey) * [disconnectModelenceQueryClient](/api-reference/modelence/client/functions/disconnectModelenceQueryClient) * [getConfig](/api-reference/modelence/client/functions/getConfig) * [getLocalStorageSession](/api-reference/modelence/client/functions/getLocalStorageSession) * [getWebsocketClientProvider](/api-reference/modelence/client/functions/getWebsocketClientProvider) * [linkOAuthProvider](/api-reference/modelence/client/functions/linkOAuthProvider) * [loginWithMagicLink](/api-reference/modelence/client/functions/loginWithMagicLink) * [loginWithOAuth](/api-reference/modelence/client/functions/loginWithOAuth) * [loginWithOneTimeCode](/api-reference/modelence/client/functions/loginWithOneTimeCode) * [loginWithPassword](/api-reference/modelence/client/functions/loginWithPassword) * [logout](/api-reference/modelence/client/functions/logout) * [modelenceLiveQuery](/api-reference/modelence/client/functions/modelenceLiveQuery) * [modelenceMutation](/api-reference/modelence/client/functions/modelenceMutation) * [modelenceQuery](/api-reference/modelence/client/functions/modelenceQuery) * [ModelenceQueryProvider](/api-reference/modelence/client/functions/ModelenceQueryProvider) * [parseDeepLinkParams](/api-reference/modelence/client/functions/parseDeepLinkParams) * [renderApp](/api-reference/modelence/client/functions/renderApp) * [resendEmailVerification](/api-reference/modelence/client/functions/resendEmailVerification) * [resetPassword](/api-reference/modelence/client/functions/resetPassword) * [resumeOAuthPopup](/api-reference/modelence/client/functions/resumeOAuthPopup) * [sendMagicLink](/api-reference/modelence/client/functions/sendMagicLink) * [sendResetPasswordToken](/api-reference/modelence/client/functions/sendResetPasswordToken) * [setWebsocketClientProvider](/api-reference/modelence/client/functions/setWebsocketClientProvider) * [signInWithOAuth](/api-reference/modelence/client/functions/signInWithOAuth) * [signupWithPassword](/api-reference/modelence/client/functions/signupWithPassword) * [startWebsockets](/api-reference/modelence/client/functions/startWebsockets) * [subscribeLiveQuery](/api-reference/modelence/client/functions/subscribeLiveQuery) * [unlinkOAuthProvider](/api-reference/modelence/client/functions/unlinkOAuthProvider) * [updateProfile](/api-reference/modelence/client/functions/updateProfile) * [useSession](/api-reference/modelence/client/functions/useSession) * [verifyEmail](/api-reference/modelence/client/functions/verifyEmail) ## References ### ValueType Re-exports [ValueType](/api-reference/modelence/client/../server/type-aliases/ValueType) # ClientConfig Source: https://docs.modelence.com/api-reference/modelence/client/interfaces/ClientConfig [API Reference](/api-reference/modelence/client/interfaces/../../../index) / [modelence](/api-reference/modelence/client/interfaces/../../index) / [client](/api-reference/modelence/client/interfaces/../index) / ClientConfig Defined in: [packages/modelence/src/client/clientConfig.ts:3](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L3) ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `baseUrl` | `string` | - | [packages/modelence/src/client/clientConfig.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L4) | | `credentials?` | `RequestCredentials` | Credentials mode for method-call requests. Defaults to `'include'`, which browser apps need for the cookie-based flows (password reset, magic link). Clients configured with token-in-body auth (React Native / Expo) never use cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin request is otherwise blocked by any server answering `Access-Control-Allow-Origin: *`, surfacing as "TypeError: Failed to fetch". | [packages/modelence/src/client/clientConfig.ts:31](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L31) | | `getAuthToken` | () => `undefined` \| `string` | - | [packages/modelence/src/client/clientConfig.ts:5](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L5) | | `getClientInfo` | () => `ClientInfo` | - | [packages/modelence/src/client/clientConfig.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L7) | | `openUrl?` | (`url`) => `unknown` | Opens a URL for OAuth redirects. React Native must use `(url) => Linking.openURL(url)` — WebView is not supported. Defaults to `window.location.href` when not provided. A web client that opens the flow in a popup should return the window `window.open` gave it: `(url) => window.open(url)`. With that reference the callback page in the popup can hand the sign-in code back to this page, which then completes the login in its own context — what makes OAuth work when the app runs inside a cross-origin iframe and the popup's storage is partitioned away from it. Any other return value (including the `Promise` from `Linking.openURL`) is ignored. | [packages/modelence/src/client/clientConfig.ts:21](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L21) | | `setAuthToken` | (`token`) => `void` | - | [packages/modelence/src/client/clientConfig.ts:6](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/clientConfig.ts#L6) | # CallMethodOptions Source: https://docs.modelence.com/api-reference/modelence/client/type-aliases/CallMethodOptions [API Reference](/api-reference/modelence/client/type-aliases/../../../index) / [modelence](/api-reference/modelence/client/type-aliases/../../index) / [client](/api-reference/modelence/client/type-aliases/../index) / CallMethodOptions > **CallMethodOptions** = `object` Defined in: [packages/modelence/src/client/method.ts:35](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L35) ## Properties | Property | Type | Defined in | | - | - | - | | `errorHandler?` | (`error`, `methodName`) => `void` | [packages/modelence/src/client/method.ts:36](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L36) | # MethodArgs Source: https://docs.modelence.com/api-reference/modelence/client/type-aliases/MethodArgs [API Reference](/api-reference/modelence/client/type-aliases/../../../index) / [modelence](/api-reference/modelence/client/type-aliases/../../index) / [client](/api-reference/modelence/client/type-aliases/../index) / MethodArgs > **MethodArgs** = `Record`\<`string`, `unknown`> Defined in: [packages/modelence/src/client/method.ts:33](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/method.ts#L33) # ModelenceQueryKey Source: https://docs.modelence.com/api-reference/modelence/client/type-aliases/ModelenceQueryKey [API Reference](/api-reference/modelence/client/type-aliases/../../../index) / [modelence](/api-reference/modelence/client/type-aliases/../../index) / [client](/api-reference/modelence/client/type-aliases/../index) / ModelenceQueryKey > **ModelenceQueryKey**\<`T`, `U`> = readonly \[`T`, `U`] Defined in: [packages/modelence/src/client/query.ts:209](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/query.ts#L209) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` *extends* `string` | - | | `U` *extends* `Args` | `Args` | # UserInfo Source: https://docs.modelence.com/api-reference/modelence/client/type-aliases/UserInfo [API Reference](/api-reference/modelence/client/type-aliases/../../../index) / [modelence](/api-reference/modelence/client/type-aliases/../../index) / [client](/api-reference/modelence/client/type-aliases/../index) / UserInfo > **UserInfo** = `object` Defined in: [packages/modelence/src/auth/client/index.ts:21](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L21) ## Properties | Property | Type | Defined in | | - | - | - | | `avatarUrl?` | `string` | [packages/modelence/src/auth/client/index.ts:29](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L29) | | `firstName?` | `string` | [packages/modelence/src/auth/client/index.ts:27](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L27) | | `handle` | `string` | [packages/modelence/src/auth/client/index.ts:23](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L23) | | `hasRole` | (`role`) => `boolean` | [packages/modelence/src/auth/client/index.ts:25](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L25) | | `id` | `string` | [packages/modelence/src/auth/client/index.ts:22](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L22) | | `lastName?` | `string` | [packages/modelence/src/auth/client/index.ts:28](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L28) | | `requireRole` | (`role`) => `void` | [packages/modelence/src/auth/client/index.ts:26](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L26) | | `roles` | `string`\[] | [packages/modelence/src/auth/client/index.ts:24](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/client/index.ts#L24) | # AppProvider Source: https://docs.modelence.com/api-reference/modelence/client/variables/AppProvider [API Reference](/api-reference/modelence/client/variables/../../../index) / [modelence](/api-reference/modelence/client/variables/../../index) / [client](/api-reference/modelence/client/variables/../index) / AppProvider > `const` **AppProvider**: `any` Defined in: [packages/modelence/src/client.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client.ts#L11) # systemConfig Source: https://docs.modelence.com/api-reference/modelence/client/variables/systemConfig [API Reference](/api-reference/modelence/client/variables/../../../index) / [modelence](/api-reference/modelence/client/variables/../../index) / [client](/api-reference/modelence/client/variables/../index) / systemConfig > `const` **systemConfig**: `object` Defined in: [packages/modelence/src/system/client.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/system/client.ts#L4) ## Type declaration | Name | Type | Description | Defined in | | - | - | - | - | | `getConfig()` | (`key`) => `undefined` \| `PublicKeyOf`\<\{ `env.type`: \{ `default`: `string`; `isPublic`: `true`; `type`: `"string"`; }; `mongodbPoolSize`: \{ `default`: `number`; `isPublic`: `false`; `type`: `"number"`; }; `mongodbUri`: \{ `default`: `string`; `isPublic`: `false`; `type`: `"secret"`; }; `multiInstance`: \{ `default`: `false`; `isPublic`: `false`; `type`: `"boolean"`; }; `site.url`: \{ `default`: `string`; `isPublic`: `true`; `type`: `"string"`; }; }>\[`K`] | - | [packages/modelence/src/client/module.ts:90](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L90) | | `infiniteQuery()` | (`name`, `getArgs`) => `object` | Returns options for `useInfiniteQuery`. The `getArgs` callback receives the current `pageParam` and returns the args to pass to the query handler. Spread the result into `useInfiniteQuery` alongside `getNextPageParam`. Annotate the `pageParam` type in the callback so TypeScript can infer the page param type — no manual generic needed on `useInfiniteQuery`. | [packages/modelence/src/client/module.ts:134](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L134) | | `mutation()` | (`name`) => `object` | - | [packages/modelence/src/client/module.ts:114](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L114) | | `query()` | (`name`, ...`rest`) => `object` | - | [packages/modelence/src/client/module.ts:97](https://github.com/modelence/modelence/blob/main/packages/modelence/src/client/module.ts#L97) | # modelence Source: https://docs.modelence.com/api-reference/modelence/index [API Reference](/api-reference/modelence/../index) / modelence ## Modules * [client](/api-reference/modelence/client/index) * [index](/api-reference/modelence/index/index) * [server](/api-reference/modelence/server/index) # AuthError Source: https://docs.modelence.com/api-reference/modelence/index/classes/AuthError [API Reference](/api-reference/modelence/index/classes/../../../index) / [modelence](/api-reference/modelence/index/classes/../../index) / [index](/api-reference/modelence/index/classes/../index) / AuthError Defined in: [packages/modelence/src/error.ts:10](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L10) ## Extends * [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError) ## Constructors ### Constructor > **new AuthError**(`message`, `code?`): `AuthError` Defined in: [packages/modelence/src/error.ts:13](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L13) #### Parameters | Parameter | Type | | - | - | | `message` | `string` | | `code?` | `string` | #### Returns `AuthError` #### Overrides [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`constructor`](ModelenceError#constructor) ## Properties | Property | Type | Default value | Description | Overrides | Inherited from | Defined in | | - | - | - | - | - | - | - | | `code?` | `string` | `undefined` | Optional machine-readable error code so clients can branch on the kind of error without string-matching `message` (which may be reworded or localized). | - | [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`code`](ModelenceError#code) | [packages/modelence/src/error.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L7) | | `status` | `number` | `401` | - | [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`status`](ModelenceError#status) | - | [packages/modelence/src/error.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L11) | # ModelenceError Source: https://docs.modelence.com/api-reference/modelence/index/classes/ModelenceError [API Reference](/api-reference/modelence/index/classes/../../../index) / [modelence](/api-reference/modelence/index/classes/../../index) / [index](/api-reference/modelence/index/classes/../index) / ModelenceError Defined in: [packages/modelence/src/error.ts:1](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L1) ## Extends * `Error` ## Extended by * [`AuthError`](/api-reference/modelence/index/classes/AuthError) * [`ValidationError`](/api-reference/modelence/index/classes/ValidationError) * [`RateLimitError`](/api-reference/modelence/index/classes/RateLimitError) ## Constructors ### Constructor > **new ModelenceError**(`message?`): `ModelenceError` Defined in: docs/gen/node_modules/typescript/lib/lib.es5.d.ts:1082 #### Parameters | Parameter | Type | | - | - | | `message?` | `string` | #### Returns `ModelenceError` #### Inherited from `Error.constructor` ## Properties | Property | Modifier | Type | Description | Defined in | | - | - | - | - | - | | `code?` | `public` | `string` | Optional machine-readable error code so clients can branch on the kind of error without string-matching `message` (which may be reworded or localized). | [packages/modelence/src/error.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L7) | | `status` | `abstract` | `number` | - | [packages/modelence/src/error.ts:2](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L2) | # RateLimitError Source: https://docs.modelence.com/api-reference/modelence/index/classes/RateLimitError [API Reference](/api-reference/modelence/index/classes/../../../index) / [modelence](/api-reference/modelence/index/classes/../../index) / [index](/api-reference/modelence/index/classes/../index) / RateLimitError Defined in: [packages/modelence/src/error.ts:30](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L30) ## Extends * [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError) ## Constructors ### Constructor > **new RateLimitError**(`message`): `RateLimitError` Defined in: [packages/modelence/src/error.ts:33](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L33) #### Parameters | Parameter | Type | | - | - | | `message` | `string` | #### Returns `RateLimitError` #### Overrides [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`constructor`](ModelenceError#constructor) ## Properties | Property | Type | Default value | Description | Overrides | Inherited from | Defined in | | - | - | - | - | - | - | - | | `code?` | `string` | `undefined` | Optional machine-readable error code so clients can branch on the kind of error without string-matching `message` (which may be reworded or localized). | - | [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`code`](ModelenceError#code) | [packages/modelence/src/error.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L7) | | `status` | `number` | `429` | - | [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`status`](ModelenceError#status) | - | [packages/modelence/src/error.ts:31](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L31) | # ValidationError Source: https://docs.modelence.com/api-reference/modelence/index/classes/ValidationError [API Reference](/api-reference/modelence/index/classes/../../../index) / [modelence](/api-reference/modelence/index/classes/../../index) / [index](/api-reference/modelence/index/classes/../index) / ValidationError Defined in: [packages/modelence/src/error.ts:20](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L20) ## Extends * [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError) ## Constructors ### Constructor > **new ValidationError**(`message`, `code?`): `ValidationError` Defined in: [packages/modelence/src/error.ts:23](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L23) #### Parameters | Parameter | Type | | - | - | | `message` | `string` | | `code?` | `string` | #### Returns `ValidationError` #### Overrides [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`constructor`](ModelenceError#constructor) ## Properties | Property | Type | Default value | Description | Overrides | Inherited from | Defined in | | - | - | - | - | - | - | - | | `code?` | `string` | `undefined` | Optional machine-readable error code so clients can branch on the kind of error without string-matching `message` (which may be reworded or localized). | - | [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`code`](ModelenceError#code) | [packages/modelence/src/error.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L7) | | `status` | `number` | `400` | - | [`ModelenceError`](/api-reference/modelence/index/classes/ModelenceError).[`status`](ModelenceError#status) | - | [packages/modelence/src/error.ts:21](https://github.com/modelence/modelence/blob/main/packages/modelence/src/error.ts#L21) | # index Source: https://docs.modelence.com/api-reference/modelence/index/index [API Reference](/api-reference/modelence/index/../../index) / [modelence](/api-reference/modelence/index/../index) / index ## Classes * [AuthError](/api-reference/modelence/index/classes/AuthError) * [ModelenceError](/api-reference/modelence/index/classes/ModelenceError) * [RateLimitError](/api-reference/modelence/index/classes/RateLimitError) * [ValidationError](/api-reference/modelence/index/classes/ValidationError) ## Interfaces * [ModelenceConfig](/api-reference/modelence/index/interfaces/ModelenceConfig) * [WebsocketClientProvider](/api-reference/modelence/index/interfaces/WebsocketClientProvider) * [WebsocketServerProvider](/api-reference/modelence/index/interfaces/WebsocketServerProvider) ## Type Aliases * [ConfigSchema](/api-reference/modelence/index/type-aliases/ConfigSchema) ## Variables * [time](/api-reference/modelence/index/variables/time) # ModelenceConfig Source: https://docs.modelence.com/api-reference/modelence/index/interfaces/ModelenceConfig [API Reference](/api-reference/modelence/index/interfaces/../../../index) / [modelence](/api-reference/modelence/index/interfaces/../../index) / [index](/api-reference/modelence/index/interfaces/../index) / ModelenceConfig Defined in: [packages/modelence/src/types/index.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/types/index.ts#L4) ## Properties | Property | Type | Defined in | | - | - | - | | `postBuildCommand?` | `string` | [packages/modelence/src/types/index.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/types/index.ts#L7) | | `serverDir` | `string` | [packages/modelence/src/types/index.ts:5](https://github.com/modelence/modelence/blob/main/packages/modelence/src/types/index.ts#L5) | | `serverEntry` | `string` | [packages/modelence/src/types/index.ts:6](https://github.com/modelence/modelence/blob/main/packages/modelence/src/types/index.ts#L6) | # WebsocketClientProvider Source: https://docs.modelence.com/api-reference/modelence/index/interfaces/WebsocketClientProvider [API Reference](/api-reference/modelence/index/interfaces/../../../index) / [modelence](/api-reference/modelence/index/interfaces/../../index) / [index](/api-reference/modelence/index/interfaces/../index) / WebsocketClientProvider Defined in: [packages/modelence/src/websocket/types.ts:10](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L10) ## Methods ### emit() > **emit**(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:15](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L15) #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `eventName`: `string`; `id`: `string`; } | | `props.category` | `string` | | `props.eventName` | `string` | | `props.id` | `string` | #### Returns `void` *** ### init() > **init**(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L11) #### Parameters | Parameter | Type | | - | - | | `props` | \{ `channels?`: [`ClientChannel`](/api-reference/modelence/index/interfaces/../../client/classes/ClientChannel)\<`unknown`>\[]; } | | `props.channels?` | [`ClientChannel`](/api-reference/modelence/index/interfaces/../../client/classes/ClientChannel)\<`unknown`>\[] | #### Returns `void` *** ### joinChannel() > **joinChannel**(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:16](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L16) #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `id`: `string`; } | | `props.category` | `string` | | `props.id` | `string` | #### Returns `void` *** ### leaveChannel() > **leaveChannel**(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:17](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L17) #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `id`: `string`; } | | `props.category` | `string` | | `props.id` | `string` | #### Returns `void` *** ### off() > **off**\<`T`>(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:14](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L14) #### Type Parameters | Type Parameter | | - | | `T` | #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `listener`: (`data`) => `void`; } | | `props.category` | `string` | | `props.listener` | (`data`) => `void` | #### Returns `void` *** ### on() > **on**\<`T`>(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:12](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L12) #### Type Parameters | Type Parameter | | - | | `T` | #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `listener`: (`data`) => `void`; } | | `props.category` | `string` | | `props.listener` | (`data`) => `void` | #### Returns `void` *** ### once() > **once**\<`T`>(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:13](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L13) #### Type Parameters | Type Parameter | | - | | `T` | #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `listener`: (`data`) => `void`; } | | `props.category` | `string` | | `props.listener` | (`data`) => `void` | #### Returns `void` *** ### reconnect()? > `optional` **reconnect**(): `void` Defined in: [packages/modelence/src/websocket/types.ts:18](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L18) #### Returns `void` # WebsocketServerProvider Source: https://docs.modelence.com/api-reference/modelence/index/interfaces/WebsocketServerProvider [API Reference](/api-reference/modelence/index/interfaces/../../../index) / [modelence](/api-reference/modelence/index/interfaces/../../index) / [index](/api-reference/modelence/index/interfaces/../index) / WebsocketServerProvider Defined in: [packages/modelence/src/websocket/types.ts:5](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L5) ## Methods ### broadcast() > **broadcast**\<`T`>(`props`): `void` Defined in: [packages/modelence/src/websocket/types.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L7) #### Type Parameters | Type Parameter | | - | | `T` | #### Parameters | Parameter | Type | | - | - | | `props` | \{ `category`: `string`; `data`: `T`; `id`: `string`; } | | `props.category` | `string` | | `props.data` | `T` | | `props.id` | `string` | #### Returns `void` *** ### init() > **init**(`props`): `Promise`\<`void`> Defined in: [packages/modelence/src/websocket/types.ts:6](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/types.ts#L6) #### Parameters | Parameter | Type | | - | - | | `props` | \{ `channels`: [`ServerChannel`](/api-reference/modelence/index/interfaces/../../server/classes/ServerChannel)\<`unknown`>\[]; `httpServer`: `Server`; } | | `props.channels` | [`ServerChannel`](/api-reference/modelence/index/interfaces/../../server/classes/ServerChannel)\<`unknown`>\[] | | `props.httpServer` | `Server` | #### Returns `Promise`\<`void`> # ConfigSchema Source: https://docs.modelence.com/api-reference/modelence/index/type-aliases/ConfigSchema [API Reference](/api-reference/modelence/index/type-aliases/../../../index) / [modelence](/api-reference/modelence/index/type-aliases/../../index) / [index](/api-reference/modelence/index/type-aliases/../index) / ConfigSchema > **ConfigSchema** = `object` Defined in: [packages/modelence/src/config/types.ts:81](https://github.com/modelence/modelence/blob/main/packages/modelence/src/config/types.ts#L81) Defines the configuration schema for a module. Each key becomes a namespaced config value accessible via `getConfig('moduleName.key')`. ## Example ```ts theme={null} import { Module } from 'modelence/server'; export default new Module('payments', { configSchema: { apiKey: { type: 'secret', default: '', isPublic: false, }, currency: { type: 'string', default: 'USD', isPublic: true, }, }, }); ``` ## Index Signature \[`key`: `string`]: `ConfigParams`\<[`ConfigType`](/api-reference/modelence/index/type-aliases/../../server/type-aliases/ConfigType), `boolean`> # time Source: https://docs.modelence.com/api-reference/modelence/index/variables/time [API Reference](/api-reference/modelence/index/variables/../../../index) / [modelence](/api-reference/modelence/index/variables/../../index) / [index](/api-reference/modelence/index/variables/../index) / time > `const` **time**: `object` Defined in: [packages/modelence/src/time.ts:7](https://github.com/modelence/modelence/blob/main/packages/modelence/src/time.ts#L7) ## Type declaration | Name | Type | Defined in | | - | - | - | | `days()` | (`x`) => `number` | [packages/modelence/src/time.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/time.ts#L11) | | `hours()` | (`x`) => `number` | [packages/modelence/src/time.ts:10](https://github.com/modelence/modelence/blob/main/packages/modelence/src/time.ts#L10) | | `minutes()` | (`x`) => `number` | [packages/modelence/src/time.ts:9](https://github.com/modelence/modelence/blob/main/packages/modelence/src/time.ts#L9) | | `seconds()` | (`x`) => `number` | [packages/modelence/src/time.ts:8](https://github.com/modelence/modelence/blob/main/packages/modelence/src/time.ts#L8) | | `weeks()` | (`x`) => `number` | [packages/modelence/src/time.ts:12](https://github.com/modelence/modelence/blob/main/packages/modelence/src/time.ts#L12) | # LiveData Source: https://docs.modelence.com/api-reference/modelence/server/classes/LiveData [API Reference](/api-reference/modelence/server/classes/../../../index) / [modelence](/api-reference/modelence/server/classes/../../index) / [server](/api-reference/modelence/server/classes/../index) / LiveData Defined in: [packages/modelence/src/live-query/context.ts:65](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L65) LiveData object returned by live query handlers. ## Example ```typescript theme={null} import { LiveData } from 'modelence/server'; ... getTodos({ userId }, context) { return new LiveData({ fetch: async () => await dbTodos.fetch({ userId }), watch: ({ publish }) => { // Subscribe to changes and call publish when data changes listener.onChange(publish); return () => { // Cleanup function to unsubscribe from changes }; } }); } ``` ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Constructors ### Constructor > **new LiveData**\<`T`>(`config`): `LiveData`\<`T`> Defined in: [packages/modelence/src/live-query/context.ts:69](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L69) #### Parameters | Parameter | Type | | - | - | | `config` | [`LiveDataConfig`](/api-reference/modelence/server/classes/../interfaces/LiveDataConfig)\<`T`> | #### Returns `LiveData`\<`T`> ## Properties | Property | Modifier | Type | Defined in | | - | - | - | - | | `fetch` | `readonly` | () => `T` \| `Promise`\<`T`> | [packages/modelence/src/live-query/context.ts:66](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L66) | | `watch` | `readonly` | [`LiveQueryWatch`](/api-reference/modelence/server/classes/../type-aliases/LiveQueryWatch) | [packages/modelence/src/live-query/context.ts:67](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L67) | # Module Source: https://docs.modelence.com/api-reference/modelence/server/classes/Module [API Reference](/api-reference/modelence/server/classes/../../../index) / [modelence](/api-reference/modelence/server/classes/../../index) / [server](/api-reference/modelence/server/classes/../index) / Module Defined in: [packages/modelence/src/app/module.ts:43](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/module.ts#L43) The Module class is a core building block of a Modelence application that encapsulates related functionality. Modules can contain stores, queries, mutations, routes, cron jobs and configurations. ## Example ```ts theme={null} const todoModule = new Module('todo', { stores: [dbTodos], queries: { async getAll() { // Fetch and return all Todo items } }, mutations: { async create({ title }, { user }) { // Create a new Todo item } } }); ``` ## Type Parameters | Type Parameter | Default type | | - | - | | `TName` *extends* `string` | `string` | | `TSchema` *extends* `Record`\<`string`, `ConfigParams`> | [`ConfigSchema`](/api-reference/modelence/server/classes/../../index/type-aliases/ConfigSchema) | | `TQueries` *extends* `Queries` | `Queries` | | `TMutations` *extends* `Mutations` | `Mutations` | ## Constructors ### Constructor > **new Module**\<`TName`, `TSchema`, `TQueries`, `TMutations`>(`name`, `options`): `Module`\<`TName`, `TSchema`, `TQueries`, `TMutations`> Defined in: [packages/modelence/src/app/module.ts:85](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/module.ts#L85) Creates a new Module instance #### Parameters | Parameter | Type | Description | | - | - | - | | `name` | `TName` | The unique name of the module. This name is used to namespace queries, mutations, cron jobs and configuration values with a prefix (e.g. "todo.create") | | `options` | \{ `channels?`: [`ServerChannel`](/api-reference/modelence/server/classes/ServerChannel)\<`unknown`>\[]; `configSchema?`: `TSchema`; `cronJobs?`: `Record`\<`string`, [`CronJobInputParams`](/api-reference/modelence/server/classes/../type-aliases/CronJobInputParams)>; `mutations?`: `TMutations`; `queries?`: `TQueries`; `rateLimits?`: [`RateLimitRule`](/api-reference/modelence/server/classes/../type-aliases/RateLimitRule)\[]; `routes?`: [`RouteDefinition`](/api-reference/modelence/server/classes/../type-aliases/RouteDefinition)\[]; `stores?`: [`Store`](/api-reference/modelence/server/classes/Store)\<`any`, `any`>\[]; } | Module configuration options | | `options.channels?` | [`ServerChannel`](/api-reference/modelence/server/classes/ServerChannel)\<`unknown`>\[] | - | | `options.configSchema?` | `TSchema` | - | | `options.cronJobs?` | `Record`\<`string`, [`CronJobInputParams`](/api-reference/modelence/server/classes/../type-aliases/CronJobInputParams)> | - | | `options.mutations?` | `TMutations` | - | | `options.queries?` | `TQueries` | - | | `options.rateLimits?` | [`RateLimitRule`](/api-reference/modelence/server/classes/../type-aliases/RateLimitRule)\[] | - | | `options.routes?` | [`RouteDefinition`](/api-reference/modelence/server/classes/../type-aliases/RouteDefinition)\[] | - | | `options.stores?` | [`Store`](/api-reference/modelence/server/classes/Store)\<`any`, `any`>\[] | - | #### Returns `Module`\<`TName`, `TSchema`, `TQueries`, `TMutations`> ## Methods ### getConfig() > **getConfig**\<`K`>(`key`): [`ValueType`](/api-reference/modelence/server/classes/../type-aliases/ValueType)\<`TSchema`\[`K`]\[`"type"`]> Defined in: [packages/modelence/src/app/module.ts:139](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/module.ts#L139) Retrieves a typed configuration value for this module. The return type is inferred from the schema — no casts needed. #### Example ```ts theme={null} const myModule = new Module('payments', { configSchema: { apiKey: { type: 'secret', default: '', isPublic: false }, maxRetries: { type: 'number', default: 3, isPublic: false }, }, mutations: { async charge({ amount }) { const apiKey = myModule.getConfig('apiKey'); // string const maxRetries = myModule.getConfig('maxRetries'); // number }, }, }); ``` #### Type Parameters | Type Parameter | | - | | `K` *extends* `string` | #### Parameters | Parameter | Type | | - | - | | `key` | `K` | #### Returns [`ValueType`](/api-reference/modelence/server/classes/../type-aliases/ValueType)\<`TSchema`\[`K`]\[`"type"`]> # ServerChannel Source: https://docs.modelence.com/api-reference/modelence/server/classes/ServerChannel [API Reference](/api-reference/modelence/server/classes/../../../index) / [modelence](/api-reference/modelence/server/classes/../../index) / [server](/api-reference/modelence/server/classes/../index) / ServerChannel Defined in: [packages/modelence/src/websocket/serverChannel.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/serverChannel.ts#L11) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Constructors ### Constructor > **new ServerChannel**\<`T`>(`category`, `canAccessChannel?`): `ServerChannel`\<`T`> Defined in: [packages/modelence/src/websocket/serverChannel.ts:15](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/serverChannel.ts#L15) #### Parameters | Parameter | Type | | - | - | | `category` | `string` | | `canAccessChannel?` | `canAccessChannel` | #### Returns `ServerChannel`\<`T`> ## Properties | Property | Modifier | Type | Defined in | | - | - | - | - | | `canAccessChannel` | `readonly` | `null` \| `canAccessChannel` | [packages/modelence/src/websocket/serverChannel.ts:13](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/serverChannel.ts#L13) | | `category` | `readonly` | `string` | [packages/modelence/src/websocket/serverChannel.ts:12](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/serverChannel.ts#L12) | ## Methods ### broadcast() > **broadcast**(`id`, `data`): `void` Defined in: [packages/modelence/src/websocket/serverChannel.ts:20](https://github.com/modelence/modelence/blob/main/packages/modelence/src/websocket/serverChannel.ts#L20) #### Parameters | Parameter | Type | | - | - | | `id` | `string` | | `data` | `T` | #### Returns `void` # Store Source: https://docs.modelence.com/api-reference/modelence/server/classes/Store [API Reference](/api-reference/modelence/server/classes/../../../index) / [modelence](/api-reference/modelence/server/classes/../../index) / [server](/api-reference/modelence/server/classes/../index) / Store Defined in: [packages/modelence/src/data/store.ts:484](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L484) The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods. ## Example ```ts theme={null} const dbTodos = new Store('todos', { schema: { title: schema.string(), completed: schema.boolean(), dueDate: schema.date().optional(), userId: schema.userId(), }, methods: { isOverdue() { return this.dueDate < new Date(); } } }); ``` ## Type Parameters | Type Parameter | Description | | - | - | | `TSchema` *extends* `ModelSchema` | The document schema type | | `TMethods` *extends* `Record`\<`string`, (`this`, ...`args`) => `any`> | Custom methods that will be added to documents | ## Constructors ### Constructor > **new Store**\<`TSchema`, `TMethods`>(`name`, `options`): `Store`\<`TSchema`, `TMethods`> Defined in: [packages/modelence/src/data/store.ts:520](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L520) Creates a new Store instance #### Parameters | Parameter | Type | Description | | - | - | - | | `name` | `string` | The collection name in MongoDB | | `options` | \{ `indexCreationMode?`: `IndexCreationMode`; `indexes`: `IndexDescription`\[]; `methods?`: `TMethods`; `schema`: `TSchema`; `searchIndexes?`: `SearchIndexDescription`\[]; } | Store configuration (schema, indexes, methods, search indexes, and optional index creation mode) | | `options.indexCreationMode?` | `IndexCreationMode` | Whether index creation should block startup or run in background (default: 'background') | | `options.indexes` | `IndexDescription`\[] | MongoDB indexes to create | | `options.methods?` | `TMethods` | Custom methods to add to documents | | `options.schema` | `TSchema` | Document schema using Modelence schema types | | `options.searchIndexes?` | `SearchIndexDescription`\[] | MongoDB Atlas Search | #### Returns `Store`\<`TSchema`, `TMethods`> ## Properties | Property | Modifier | Type | Defined in | | - | - | - | - | | `Doc` | `readonly` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods` | [packages/modelence/src/data/store.ts:499](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L499) | ## Methods ### aggregate() > **aggregate**(`pipeline`, `options?`): `AggregationCursor`\<`Document`> Defined in: [packages/modelence/src/data/store.ts:1352](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1352) Aggregates documents using MongoDB's aggregation framework #### Parameters | Parameter | Type | Description | | - | - | - | | `pipeline` | `Document`\[] | The aggregation pipeline | | `options?` | `AggregateOptions` | Optional options | #### Returns `AggregationCursor`\<`Document`> The aggregation cursor *** ### bulkWrite() > **bulkWrite**(`operations`): `Promise`\<`BulkWriteResult`> Defined in: [packages/modelence/src/data/store.ts:1362](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1362) Performs a bulk write operation on the collection #### Parameters | Parameter | Type | Description | | - | - | - | | `operations` | `AnyBulkWriteOperation`\<`InferDocumentType`\<`TSchema`>>\[] | The operations to perform | #### Returns `Promise`\<`BulkWriteResult`> The result of the bulk write operation *** ### countDocuments() > **countDocuments**(`query`): `Promise`\<`number`> Defined in: [packages/modelence/src/data/store.ts:996](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L996) Counts the number of documents that match a query #### Parameters | Parameter | Type | Description | | - | - | - | | `query` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The query to filter documents | #### Returns `Promise`\<`number`> The number of documents that match the query *** ### create() > **create**(`document`, `options?`): `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:1065](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1065) Inserts a single document and returns the inserted document with its generated `_id` and any helper methods applied. Unlike [insertOne](/api-reference/modelence/server/classes/Store#insertone), which only returns the insert result metadata, this method returns the full inserted document — useful when you need to immediately use the newly created record (e.g. returning it from an API handler). #### Example ```ts theme={null} const todo = await dbTodos.create({ title: 'Buy milk', completed: false }); console.log(todo._id); // ObjectId console.log(todo.title); // 'Buy milk' ``` #### Parameters | Parameter | Type | Description | | - | - | - | | `document` | `OptionalUnlessRequiredId`\<`InferDocumentType`\<`TSchema`>> | The document to insert | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The inserted document with `_id` populated and methods applied *** ### deleteMany() > **deleteMany**(`selector`, `options?`): `Promise`\<`DeleteResult`> Defined in: [packages/modelence/src/data/store.ts:1181](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1181) Deletes multiple documents #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the documents to delete | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`DeleteResult`> The result of the delete operation *** ### deleteOne() > **deleteOne**(`selector`, `options?`): `Promise`\<`DeleteResult`> Defined in: [packages/modelence/src/data/store.ts:1168](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1168) Deletes a single document #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document to delete | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`DeleteResult`> The result of the delete operation *** ### distinct() > **distinct**\<`K`>(`key`, `filter?`, `options?`): `Promise`\<`Flatten`\<`WithId`\<`InferDocumentType`\<`TSchema`>>\[`K`]>\[]> Defined in: [packages/modelence/src/data/store.ts:1323](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1323) Returns an array of distinct values for a field across the collection #### Type Parameters | Type Parameter | | - | | `K` *extends* `string` | #### Parameters | Parameter | Type | Description | | - | - | - | | `key` | `K` | The field name (supports dot notation for nested fields) | | `filter?` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | Optional filter to narrow the documents | | `options?` | `DistinctOptions` | Optional distinct options | #### Returns `Promise`\<`Flatten`\<`WithId`\<`InferDocumentType`\<`TSchema`>>\[`K`]>\[]> An array of distinct values *** ### extend() > **extend**\<`TExtendedSchema`, `TExtendedMethods`>(`config`): `Store`\<`TSchema` & `TExtendedSchema`, `PreserveMethodsForExtendedSchema`\<`TMethods`, `TSchema` & `TExtendedSchema`> & `TExtendedMethods`> Defined in: [packages/modelence/src/data/store.ts:623](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L623) Extends the store with additional schema fields, indexes, methods, and search indexes. Returns a new Store instance with the extended schema and updated types. Methods from the original store are preserved with updated type signatures. #### Example ```ts theme={null} // Extend the users collection export const dbUsers = baseUsersCollection.extend({ schema: { firstName: schema.string(), lastName: schema.string(), companyId: schema.objectId().optional(), }, indexes: [ { key: { companyId: 1 } }, { key: { lastName: 1, firstName: 1 } }, ], methods: { getFullName() { return `${this.firstName} ${this.lastName}`; } } }); // Now fully typed with new fields const user = await dbUsers.findOne({ firstName: 'John' }); console.log(user?.getFullName()); ``` #### Type Parameters | Type Parameter | Default type | | - | - | | `TExtendedSchema` *extends* `ModelSchema` | - | | `TExtendedMethods` *extends* `Record`\<`string`, `Function`> | `Record`\<`string`, `never`> | #### Parameters | Parameter | Type | Description | | - | - | - | | `config` | \{ `indexCreationMode?`: `IndexCreationMode`; `indexes?`: `IndexDescription`\[]; `methods?`: `TExtendedMethods`; `schema?`: `TExtendedSchema`; `searchIndexes?`: `SearchIndexDescription`\[]; } | Additional schema fields, indexes, methods, search indexes, and optional index creation mode to add | | `config.indexCreationMode?` | `IndexCreationMode` | Whether index creation should block startup or run in background | | `config.indexes?` | `IndexDescription`\[] | - | | `config.methods?` | `TExtendedMethods` | - | | `config.schema?` | `TExtendedSchema` | - | | `config.searchIndexes?` | `SearchIndexDescription`\[] | - | #### Returns `Store`\<`TSchema` & `TExtendedSchema`, `PreserveMethodsForExtendedSchema`\<`TMethods`, `TSchema` & `TExtendedSchema`> & `TExtendedMethods`> A new Store instance with the extended schema *** ### fetch() > **fetch**(`query`, `options?`): `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`\[]> Defined in: [packages/modelence/src/data/store.ts:1026](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1026) Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined. #### Example ```ts theme={null} // Include only selected fields const docs = await store.fetch( { userId: user.id }, { projection: { framework: 1, title: 1 }, sort: { createdAt: -1 }, limit: 50 } ); // Exclude large fields when not needed const chunks = await store.fetch( { documentId }, { projection: { embedding: 0 } } ); ``` #### Parameters | Parameter | Type | Description | | - | - | - | | `query` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The query to filter documents | | `options?` | `FetchOptions`\<`InferDocumentType`\<`TSchema`>> | Optional fetch options | #### Returns `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`\[]> The documents *** ### findById() > **findById**(`id`): `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:968](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L968) Fetches a single document by its ID #### Parameters | Parameter | Type | Description | | - | - | - | | `id` | `string` \| `ObjectId` | The ID of the document to find | #### Returns `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The document, or null if not found *** ### findOne() > **findOne**(`query`, `options?`): `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:925](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L925) Finds a single document matching the query #### Example ```ts theme={null} // ✅ Valid queries: await store.findOne({ name: 'John' }) await store.findOne({ age: { $gt: 18 } }) await store.findOne({ _id: new ObjectId('...') }) await store.findOne({ tags: { $in: ['typescript', 'mongodb'] } }) await store.findOne({ $or: [{ name: 'John' }, { name: 'Jane' }] }) await store.findOne({ 'emails.address': 'test@example.com' }) // dot notation // ❌ TypeScript error - 'id' is not in schema: await store.findOne({ id: '123' }) ``` #### Parameters | Parameter | Type | Description | | - | - | - | | `query` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | Type-safe query filter. Only schema fields, MongoDB operators, and dot notation are allowed. | | `options?` | `FindOptions`\<`Document`> | Find options | #### Returns `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The document, or null if not found *** ### findOneAndDelete() > **findOneAndDelete**(`selector`, `options?`): `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:1262](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1262) Atomically finds a document and deletes it, returning the deleted document #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document | | `options?` | `Omit`\<`FindOneAndDeleteOptions`, `"includeResultMetadata"`> | Options including `session`, `projection`, etc. | #### Returns `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The deleted document, or null if not found *** ### findOneAndReplace() > **findOneAndReplace**(`selector`, `replacement`, `options?`): `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:1281](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1281) Atomically finds a document and replaces it, returning the document #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document | | `replacement` | `WithoutId`\<`this`\[`"_type"`]> | The replacement document | | `options?` | `Omit`\<`FindOneAndReplaceOptions`, `"includeResultMetadata"`> | Options including `returnDocument` ('before' or 'after'), `upsert`, `session`, etc. | #### Returns `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The document (before or after replacement, depending on options), or null if not found *** ### findOneAndUpdate() > **findOneAndUpdate**(`selector`, `update`, `options?`): `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:1196](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1196) Atomically finds a document and updates it, returning the document #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document | | `update` | `UpdateFilter`\<`InferDocumentType`\<`TSchema`>> | The update to apply | | `options?` | `Omit`\<`FindOneAndUpdateOptions`, `"includeResultMetadata"`> | Options including `returnDocument` ('before' or 'after'), `upsert`, `session`, etc. | #### Returns `Promise`\<`null` | `EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The document (before or after update, depending on options), or null if not found *** ### findOneAndUpsert() > **findOneAndUpsert**(`selector`, `update`, `options?`): `Promise`\<`UpsertResult`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`>> Defined in: [packages/modelence/src/data/store.ts:1235](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1235) Atomic find-or-create: runs `findOneAndUpdate` with `upsert` and reports, as `isNew`, whether the returned document was newly inserted. The plain [findOneAndUpdate](/api-reference/modelence/server/classes/Store#findoneandupdate) deliberately hides result metadata and returns only the document, so it can't distinguish an insert from a match. This method surfaces the driver's `lastErrorObject.upserted` flag as `isNew`, so callers can branch on create-vs-match without a separate pre-existence read that would race with concurrent upserts. `upsert` defaults to `true` but is overridable — pass `upsert: false` to make this a pure find-and-report (unknown selector → `{ doc: null, isNew: false }`). `returnDocument` is always `'after'` and cannot be overridden. #### Example ```ts theme={null} const { doc, isNew } = await dbUsers.findOneAndUpsert( { email }, { $setOnInsert: { email, createdAt: new Date() } } ); if (isNew) onSignup(doc); else onLogin(doc); ``` #### Parameters | Parameter | Type | | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | | `update` | `UpdateFilter`\<`InferDocumentType`\<`TSchema`>> | | `options?` | `Omit`\<`FindOneAndUpdateOptions`, `"includeResultMetadata"` \| `"returnDocument"`> | #### Returns `Promise`\<`UpsertResult`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`>> `{ doc, isNew }` — `doc` is null only when `upsert: false` and nothing matched; `isNew` is `true` exactly when this call inserted the doc. *** ### getDatabase() > **getDatabase**(): `Db` Defined in: [packages/modelence/src/data/store.ts:1371](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1371) Returns the raw MongoDB database instance for advanced operations #### Returns `Db` The MongoDB database instance #### Throws Error if the store is not provisioned *** ### getIndexCreationMode() > **getIndexCreationMode**(): `IndexCreationMode` Defined in: [packages/modelence/src/data/store.ts:548](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L548) #### Returns `IndexCreationMode` *** ### getName() > **getName**(): `string` Defined in: [packages/modelence/src/data/store.ts:544](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L544) #### Returns `string` *** ### insertMany() > **insertMany**(`documents`, `options?`): `Promise`\<`InsertManyResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1085](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1085) Inserts multiple documents #### Parameters | Parameter | Type | Description | | - | - | - | | `documents` | `OptionalUnlessRequiredId`\<`InferDocumentType`\<`TSchema`>>\[] | The documents to insert | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`InsertManyResult`\<`Document`>> The result of the insert operation *** ### insertOne() > **insertOne**(`document`, `options?`): `Promise`\<`InsertOneResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1040](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1040) Inserts a single document #### Parameters | Parameter | Type | Description | | - | - | - | | `document` | `OptionalUnlessRequiredId`\<`InferDocumentType`\<`TSchema`>> | The document to insert | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`InsertOneResult`\<`Document`>> The result of the insert operation *** ### rawCollection() > **rawCollection**(): `Collection`\<`InferDocumentType`\<`TSchema`>> Defined in: [packages/modelence/src/data/store.ts:1380](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1380) Returns the raw MongoDB collection instance for advanced operations #### Returns `Collection`\<`InferDocumentType`\<`TSchema`>> The MongoDB collection instance #### Throws Error if the store is not provisioned *** ### renameFrom() > **renameFrom**(`oldName`, `options?`): `Promise`\<`void`> Defined in: [packages/modelence/src/data/store.ts:1389](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1389) Renames an existing collection to this store's name, used for migrations #### Parameters | Parameter | Type | Description | | - | - | - | | `oldName` | `string` | The previous name of the collection | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`void`> #### Throws Error if the old collection doesn't exist or if this store's collection already exists *** ### replaceOne() > **replaceOne**(`selector`, `replacement`, `options?`): `Promise`\<`UpdateResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1302](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1302) Replaces a single document #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document to replace | | `replacement` | `WithoutId`\<`this`\[`"_type"`]> | The replacement document (must not contain update operators) | | `options?` | `ReplaceOptions` | Options including `upsert`, `session`, etc. | #### Returns `Promise`\<`UpdateResult`\<`Document`>> The result of the replace operation *** ### requireById() > **requireById**(`id`, `errorHandler?`): `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:980](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L980) Fetches a single document by its ID, or throws an error if not found #### Parameters | Parameter | Type | Description | | - | - | - | | `id` | `string` \| `ObjectId` | The ID of the document to find | | `errorHandler?` | () => `Error` | Optional error handler to return a custom error if the document is not found | #### Returns `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> The document *** ### requireOne() > **requireOne**(`query`, `options?`, `errorHandler?`): `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> Defined in: [packages/modelence/src/data/store.ts:933](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L933) #### Parameters | Parameter | Type | | - | - | | `query` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | | `options?` | `FindOptions`\<`Document`> | | `errorHandler?` | () => `Error` | #### Returns `Promise`\<`EnhancedOmit`\<`InferDocumentType`\<`TSchema`>, `"_id"`> & `object` & `TMethods`> *** ### updateMany() > **updateMany**(`selector`, `update`, `options?`): `Promise`\<`UpdateResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1132](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1132) Updates multiple documents #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the documents to update | | `update` | `UpdateFilter`\<`InferDocumentType`\<`TSchema`>> | The MongoDB modifier to apply to the documents | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`UpdateResult`\<`Document`>> The result of the update operation *** ### updateOne() > **updateOne**(`selector`, `update`, `options?`): `Promise`\<`UpdateResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1099](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1099) Updates a single document #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document to update | | `update` | `UpdateFilter`\<`InferDocumentType`\<`TSchema`>> | The update to apply to the document | | `options?` | \{ `collation?`: `CollationOptions`; `session?`: `ClientSession`; } | - | | `options.collation?` | `CollationOptions` | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`UpdateResult`\<`Document`>> The result of the update operation *** ### upsertMany() > **upsertMany**(`selector`, `update`, `options?`): `Promise`\<`UpdateResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1151](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1151) Updates multiple documents, or inserts them if they don't exist #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the documents to update | | `update` | `UpdateFilter`\<`InferDocumentType`\<`TSchema`>> | The MongoDB modifier to apply to the documents | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`UpdateResult`\<`Document`>> The result of the update operation *** ### upsertOne() > **upsertOne**(`selector`, `update`, `options?`): `Promise`\<`UpdateResult`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1114](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1114) Updates a single document, or inserts it if it doesn't exist #### Parameters | Parameter | Type | Description | | - | - | - | | `selector` | `string` \| `ObjectId` \| `TypedFilter`\<`InferDocumentType`\<`TSchema`>> | The selector to find the document to update | | `update` | `UpdateFilter`\<`InferDocumentType`\<`TSchema`>> | The MongoDB modifier to apply to the document | | `options?` | \{ `session?`: `ClientSession`; } | - | | `options.session?` | `ClientSession` | - | #### Returns `Promise`\<`UpdateResult`\<`Document`>> The result of the update operation *** ### vectorSearch() > **vectorSearch**(`params`): `Promise`\<`AggregationCursor`\<`Document`>> Defined in: [packages/modelence/src/data/store.ts:1434](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1434) Performs a vector similarity search using MongoDB Atlas Vector Search #### Example ```ts theme={null} const results = await store.vectorSearch({ field: 'embedding', embedding: [0.1, 0.2, 0.3, ...], numCandidates: 100, limit: 10, projection: { title: 1, description: 1 } }); ``` #### Parameters | Parameter | Type | Description | | - | - | - | | `params` | \{ `embedding`: `number`\[]; `field`: `string`; `indexName?`: `string`; `limit?`: `number`; `numCandidates?`: `number`; `projection?`: `Document`; } | Vector search parameters | | `params.embedding` | `number`\[] | The query vector to search for | | `params.field` | `string` | The field name containing the vector embeddings | | `params.indexName?` | `string` | Name of index (default: field + VectorSearch) | | `params.limit?` | `number` | Maximum number of results to return (default: 10) | | `params.numCandidates?` | `number` | Number of nearest neighbors to consider (default: 100) | | `params.projection?` | `Document` | Additional fields to include in the results | #### Returns `Promise`\<`AggregationCursor`\<`Document`>> An aggregation cursor with search results and scores *** ### watch() > **watch**(`pipeline?`, `options?`): `ChangeStream` Defined in: [packages/modelence/src/data/store.ts:1341](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1341) Opens a change stream on the collection to watch for real-time changes #### Parameters | Parameter | Type | Description | | - | - | - | | `pipeline?` | `Document`\[] | Optional aggregation pipeline to filter/transform change events | | `options?` | `ChangeStreamOptions` | Optional change stream options | #### Returns `ChangeStream` A ChangeStream instance *** ### vectorIndex() > `static` **vectorIndex**(`params`): `object` Defined in: [packages/modelence/src/data/store.ts:1497](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1497) Creates a MongoDB Atlas Vector Search index definition #### Example ```ts theme={null} const store = new Store('documents', { schema: { title: schema.string(), embedding: schema.array(schema.number()), }, indexes: [], searchIndexes: [ Store.vectorIndex({ field: 'embedding', dimensions: 1536, similarity: 'cosine' }) ] }); ``` #### Parameters | Parameter | Type | Description | | - | - | - | | `params` | \{ `dimensions`: `number`; `field`: `string`; `indexName?`: `string`; `similarity?`: `"cosine"` \| `"euclidean"` \| `"dotProduct"`; } | Vector index parameters | | `params.dimensions` | `number` | The number of dimensions in the vector embeddings | | `params.field` | `string` | The field name to create the vector index on | | `params.indexName?` | `string` | Name of index (default: field + VectorSearch) | | `params.similarity?` | `"cosine"` \| `"euclidean"` \| `"dotProduct"` | The similarity metric to use (default: 'cosine') | #### Returns `object` A search index description object | Name | Type | Default value | Defined in | | - | - | - | - | | `definition` | `object` | - | [packages/modelence/src/data/store.ts:1511](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1511) | | `definition.fields` | `object`\[] | - | [packages/modelence/src/data/store.ts:1512](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1512) | | `name` | `string` | - | [packages/modelence/src/data/store.ts:1510](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1510) | | `type` | `string` | `'vectorSearch'` | [packages/modelence/src/data/store.ts:1509](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/store.ts#L1509) | # authenticate Source: https://docs.modelence.com/api-reference/modelence/server/functions/authenticate [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / authenticate > **authenticate**(`authToken`, `__namedParameters`): `Promise`\<\{ `roles`: `string`\[]; `session`: `Session`; `user`: `null` | [`UserInfo`](/api-reference/modelence/server/functions/../type-aliases/UserInfo); }> Defined in: [packages/modelence/src/auth/index.ts:8](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/index.ts#L8) ## Parameters | Parameter | Type | | - | - | | `authToken` | `null` \| `string` | | `__namedParameters` | `ObtainSessionOptions` | ## Returns `Promise`\<\{ `roles`: `string`\[]; `session`: `Session`; `user`: `null` | [`UserInfo`](/api-reference/modelence/server/functions/../type-aliases/UserInfo); }> # clearSessionUser Source: https://docs.modelence.com/api-reference/modelence/server/functions/clearSessionUser [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / clearSessionUser > **clearSessionUser**(`authToken`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/session.ts:277](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L277) ## Parameters | Parameter | Type | | - | - | | `authToken` | `string` | ## Returns `Promise`\<`void`> # consumeRateLimit Source: https://docs.modelence.com/api-reference/modelence/server/functions/consumeRateLimit [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / consumeRateLimit > **consumeRateLimit**(`options`): `Promise`\<`void`> Defined in: [packages/modelence/src/rate-limit/rules.ts:30](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/rules.ts#L30) This function will check all rate limit rules on the specified bucket and type, throw an error if any of them are exceeded and increase the count of the rate limit record. ## Example ```ts theme={null} await consumeRateLimit({ bucket: 'api', type: 'ip', value: '127.0.0.1' }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `options` | \{ `bucket`: `string`; `message?`: `string`; `type`: [`RateLimitType`](/api-reference/modelence/server/functions/../type-aliases/RateLimitType); `value`: `string`; } | - | | `options.bucket` | `string` | The bucket for the rate limit. | | `options.message?` | `string` | Optional custom error message when the rate limit is exceeded. | | `options.type` | [`RateLimitType`](/api-reference/modelence/server/functions/../type-aliases/RateLimitType) | The type of the rate limit. | | `options.value` | `string` | The value for the rate limit. | ## Returns `Promise`\<`void`> # createQuery Source: https://docs.modelence.com/api-reference/modelence/server/functions/createQuery [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / createQuery > **createQuery**\<`T`>(`name`, `methodDef`): `void` Defined in: [packages/modelence/src/methods/index.ts:9](https://github.com/modelence/modelence/blob/main/packages/modelence/src/methods/index.ts#L9) ## Type Parameters | Type Parameter | | - | | `T` *extends* `unknown`\[] | ## Parameters | Parameter | Type | | - | - | | `name` | `string` | | `methodDef` | `MethodDefinition`\<`T`> | ## Returns `void` # createSession Source: https://docs.modelence.com/api-reference/modelence/server/functions/createSession [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / createSession > **createSession**(`userId`): `Promise`\<`Session`> Defined in: [packages/modelence/src/auth/session.ts:290](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L290) ## Parameters | Parameter | Type | Default value | | - | - | - | | `userId` | `null` \| `ObjectId` | `null` | ## Returns `Promise`\<`Session`> # deleteFile Source: https://docs.modelence.com/api-reference/modelence/server/functions/deleteFile [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / deleteFile > **deleteFile**(`filePath`): `Promise`\<`void`> Defined in: [packages/modelence/src/files/index.ts:30](https://github.com/modelence/modelence/blob/main/packages/modelence/src/files/index.ts#L30) ## Parameters | Parameter | Type | | - | - | | `filePath` | `string` | ## Returns `Promise`\<`void`> # deleteUser Source: https://docs.modelence.com/api-reference/modelence/server/functions/deleteUser [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / deleteUser > **deleteUser**(`userId`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/deleteUser.ts:60](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/deleteUser.ts#L60) ## Parameters | Parameter | Type | | - | - | | `userId` | `ObjectId` | ## Returns `Promise`\<`void`> # disableUser Source: https://docs.modelence.com/api-reference/modelence/server/functions/disableUser [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / disableUser > **disableUser**(`userId`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/deleteUser.ts:40](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/deleteUser.ts#L40) ## Parameters | Parameter | Type | | - | - | | `userId` | `ObjectId` | ## Returns `Promise`\<`void`> # downloadFile Source: https://docs.modelence.com/api-reference/modelence/server/functions/downloadFile [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / downloadFile > **downloadFile**(`filePath`): `Promise`\<`DownloadFileResult`> Defined in: [packages/modelence/src/files/index.ts:34](https://github.com/modelence/modelence/blob/main/packages/modelence/src/files/index.ts#L34) ## Parameters | Parameter | Type | | - | - | | `filePath` | `string` | ## Returns `Promise`\<`DownloadFileResult`> # getConfig Source: https://docs.modelence.com/api-reference/modelence/server/functions/getConfig [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / getConfig > **getConfig**(`key`): `undefined` | `string` | `number` | `boolean` Defined in: [packages/modelence/src/config/server.ts:43](https://github.com/modelence/modelence/blob/main/packages/modelence/src/config/server.ts#L43) ## Parameters | Parameter | Type | Description | | - | - | - | | `key` | `string` | The configuration key to retrieve | ## Returns `undefined` | `string` | `number` | `boolean` The configuration value (string, number, or boolean) ## Sidebar Title getConfig (server) ## Examples ```ts theme={null} import { getConfig } from 'modelence/server'; // Get the site URL const siteUrl = getConfig('_system.site.url'); ``` Set via environment variable: ```bash theme={null} MODELENCE_SITE_URL=https://myapp.com ``` ```ts theme={null} import { getConfig } from 'modelence/server'; // Get the current environment (e.g., 'development', 'staging', 'production') const env = getConfig('_system.env'); if (env === 'production') { // Enable production features } ``` Set via environment variable: ```bash theme={null} MODELENCE_SITE_ENV=production ``` # getEnvironmentId Source: https://docs.modelence.com/api-reference/modelence/server/functions/getEnvironmentId [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / getEnvironmentId > **getEnvironmentId**(): `undefined` | `string` Defined in: [packages/modelence/src/app/state.ts:26](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/state.ts#L26) ## Returns `undefined` | `string` # getFileUrl Source: https://docs.modelence.com/api-reference/modelence/server/functions/getFileUrl [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / getFileUrl > **getFileUrl**(`filePath`): `Promise`\<`GetFileUrlResult`> Defined in: [packages/modelence/src/files/index.ts:38](https://github.com/modelence/modelence/blob/main/packages/modelence/src/files/index.ts#L38) ## Parameters | Parameter | Type | | - | - | | `filePath` | `string` | ## Returns `Promise`\<`GetFileUrlResult`> # getUploadUrl Source: https://docs.modelence.com/api-reference/modelence/server/functions/getUploadUrl [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / getUploadUrl > **getUploadUrl**(`__namedParameters`): `Promise`\<`GetUploadUrlResult`> Defined in: [packages/modelence/src/files/index.ts:14](https://github.com/modelence/modelence/blob/main/packages/modelence/src/files/index.ts#L14) ## Parameters | Parameter | Type | | - | - | | `__namedParameters` | \{ `contentType`: `string`; `filePath`: `string`; `visibility`: [`FileVisibility`](/api-reference/modelence/server/functions/../type-aliases/FileVisibility); } | | `__namedParameters.contentType` | `string` | | `__namedParameters.filePath` | `string` | | `__namedParameters.visibility` | [`FileVisibility`](/api-reference/modelence/server/functions/../type-aliases/FileVisibility) | ## Returns `Promise`\<`GetUploadUrlResult`> # invalidateAllUserSessions Source: https://docs.modelence.com/api-reference/modelence/server/functions/invalidateAllUserSessions [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / invalidateAllUserSessions > **invalidateAllUserSessions**(`userId`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/session.ts:286](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L286) ## Parameters | Parameter | Type | | - | - | | `userId` | `ObjectId` | ## Returns `Promise`\<`void`> # isSessionSaved Source: https://docs.modelence.com/api-reference/modelence/server/functions/isSessionSaved [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / isSessionSaved > **isSessionSaved**(`session`): `boolean` Defined in: [packages/modelence/src/auth/session.ts:173](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L173) Whether the session has a record in the sessions collection. ## Parameters | Parameter | Type | | - | - | | `session` | `Session` | ## Returns `boolean` # obtainSession Source: https://docs.modelence.com/api-reference/modelence/server/functions/obtainSession [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / obtainSession > **obtainSession**(`authToken`, `__namedParameters`): `Promise`\<`Session`> Defined in: [packages/modelence/src/auth/session.ts:177](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L177) ## Parameters | Parameter | Type | | - | - | | `authToken` | `null` \| `string` | | `__namedParameters` | `ObtainSessionOptions` | ## Returns `Promise`\<`Session`> # sendEmail Source: https://docs.modelence.com/api-reference/modelence/server/functions/sendEmail [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / sendEmail > **sendEmail**(`payload`): `undefined` | `Promise`\<`void`> Defined in: [packages/modelence/src/app/email.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/email.ts#L4) ## Parameters | Parameter | Type | | - | - | | `payload` | `EmailPayload` | ## Returns `undefined` | `Promise`\<`void`> # setAuthTokenCookie Source: https://docs.modelence.com/api-reference/modelence/server/functions/setAuthTokenCookie [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / setAuthTokenCookie > **setAuthTokenCookie**(`res`, `authToken`): `void` Defined in: [packages/modelence/src/auth/session.ts:326](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L326) ## Parameters | Parameter | Type | | - | - | | `res` | `Response` | | `authToken` | `string` | ## Returns `void` # setSessionUser Source: https://docs.modelence.com/api-reference/modelence/server/functions/setSessionUser [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / setSessionUser > **setSessionUser**(`authToken`, `userId`): `Promise`\<`void`> Defined in: [packages/modelence/src/auth/session.ts:268](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L268) ## Parameters | Parameter | Type | | - | - | | `authToken` | `string` | | `userId` | `ObjectId` | ## Returns `Promise`\<`void`> # startApp Source: https://docs.modelence.com/api-reference/modelence/server/functions/startApp [API Reference](/api-reference/modelence/server/functions/../../../index) / [modelence](/api-reference/modelence/server/functions/../../index) / [server](/api-reference/modelence/server/functions/../index) / startApp > **startApp**(`__namedParameters`): `Promise`\<`void`> Defined in: [packages/modelence/src/app/index.ts:79](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L79) ## Parameters | Parameter | Type | | - | - | | `__namedParameters` | [`AppOptions`](/api-reference/modelence/server/functions/../type-aliases/AppOptions) | ## Returns `Promise`\<`void`> # server Source: https://docs.modelence.com/api-reference/modelence/server/index [API Reference](/api-reference/modelence/server/../../index) / [modelence](/api-reference/modelence/server/../index) / server ## Module * [Module](/api-reference/modelence/server/classes/Module) ## Other ### ConfigSchema Re-exports [ConfigSchema](/api-reference/modelence/server/../index/type-aliases/ConfigSchema) ## Rate Limits * [consumeRateLimit](/api-reference/modelence/server/functions/consumeRateLimit) ## Store * [Store](/api-reference/modelence/server/classes/Store) # LiveDataConfig Source: https://docs.modelence.com/api-reference/modelence/server/interfaces/LiveDataConfig [API Reference](/api-reference/modelence/server/interfaces/../../../index) / [modelence](/api-reference/modelence/server/interfaces/../../index) / [server](/api-reference/modelence/server/interfaces/../index) / LiveDataConfig Defined in: [packages/modelence/src/live-query/context.ts:30](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L30) Configuration for creating LiveData. ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `fetch` | () => `T` \| `Promise`\<`T`> | Fetches the current data. Called initially and whenever watch triggers publish. | [packages/modelence/src/live-query/context.ts:34](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L34) | | `watch` | [`LiveQueryWatch`](/api-reference/modelence/server/interfaces/../type-aliases/LiveQueryWatch) | Sets up watching for changes. Receives publish callback and returns cleanup. | [packages/modelence/src/live-query/context.ts:38](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L38) | # schema Source: https://docs.modelence.com/api-reference/modelence/server/namespaces/schema/index [API Reference](/api-reference/modelence/server/namespaces/schema/../../../../index) / [modelence](/api-reference/modelence/server/namespaces/schema/../../../index) / [server](/api-reference/modelence/server/namespaces/schema/../../index) / schema ## Type Aliases * [infer](/api-reference/modelence/server/namespaces/schema/type-aliases/infer) # infer Source: https://docs.modelence.com/api-reference/modelence/server/namespaces/schema/type-aliases/infer [API Reference](/api-reference/modelence/server/namespaces/schema/type-aliases/../../../../../index) / [modelence](/api-reference/modelence/server/namespaces/schema/type-aliases/../../../../index) / [server](/api-reference/modelence/server/namespaces/schema/type-aliases/../../../index) / [schema](/api-reference/modelence/server/namespaces/schema/type-aliases/../index) / infer > **infer**\<`T`> = `InferDocumentType`\<`T`> Defined in: [packages/modelence/src/data/types.ts:74](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L74) ## Type Parameters | Type Parameter | | - | | `T` *extends* `SchemaTypeDefinition` | # AppOptions Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/AppOptions [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / AppOptions > **AppOptions** = `object` Defined in: [packages/modelence/src/app/index.ts:47](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L47) ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `auth?` | [`AuthConfig`](/api-reference/modelence/server/type-aliases/AuthConfig) | - | [packages/modelence/src/app/index.ts:51](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L51) | | `email?` | `EmailConfig` | - | [packages/modelence/src/app/index.ts:50](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L50) | | `migrations?` | `MigrationScript`\[] | - | [packages/modelence/src/app/index.ts:72](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L72) | | `modules?` | [`Module`](/api-reference/modelence/server/type-aliases/../classes/Module)\[] | - | [packages/modelence/src/app/index.ts:48](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L48) | | `roles?` | `Record`\<`string`, [`RoleDefinition`](/api-reference/modelence/server/type-aliases/RoleDefinition)> | Custom role definitions keyed by role name. Defined roles are synced to the Modelence Cloud dashboard for user management. See [RoleDefinition](/api-reference/modelence/server/type-aliases/RoleDefinition). **Example** `startApp({ roles: { admin: { description: 'Full access to all features' }, editor: { description: 'Can edit content' }, viewer: {}, }, });` | [packages/modelence/src/app/index.ts:69](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L69) | | `security?` | [`SecurityConfig`](/api-reference/modelence/server/type-aliases/SecurityConfig) | Security settings such as clickjacking protection. See [SecurityConfig](/api-reference/modelence/server/type-aliases/SecurityConfig). | [packages/modelence/src/app/index.ts:53](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L53) | | `server?` | `AppServer` | - | [packages/modelence/src/app/index.ts:49](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L49) | | `ssr?` | `boolean` | Enable server-side rendering of the user's React tree. | [packages/modelence/src/app/index.ts:76](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L76) | | `websocket?` | `WebsocketConfig` | WebSocket settings, used by live queries and channels. See WebsocketConfig. | [packages/modelence/src/app/index.ts:74](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/index.ts#L74) | # AuthConfig Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/AuthConfig [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / AuthConfig > **AuthConfig** = `object` Defined in: [packages/modelence/src/app/authConfig.ts:218](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L218) Authentication configuration for the application The notify-only hooks (`onAfterLogin`, `onLoginError`, `onAfterSignup`, `onSignupError`, `onAfterEmailVerification`, `onEmailVerificationError`, `onAfterOAuthLink`, `onOAuthLinkError` and the deprecated `login`/`signup` callbacks) may be async, but they are not awaited: don't rely on one finishing before the client gets its response. A hook that throws or rejects is logged as `Error in hook:` and does not change the response. `onBeforeSignup` is the exception: it is awaited, and throwing from it aborts the signup. ## Example ```typescript theme={null} import { startApp } from 'modelence/server'; import { time } from 'modelence'; startApp({ auth: { validateSignup: ({ email, firstName, lastName, password, handle, avatarUrl }) => { // Validating the signup data if (!email || !password) { throw new Error('Email and password are required'); } }, onAfterLogin: ({ user }) => { console.log('User logged in:', user.name); // Redirect to dashboard }, onLoginError: ({ error }) => { console.error('Login failed:', error.message); // Show error toast }, onAfterSignup: ({ user }) => { console.log('User signed up:', user.email); // Send welcome email }, onSignupError: ({ error }) => { console.error('Signup failed:', error.message); }, generateHandle: ({ email }) => { console.log('Generating handle for:', email); // Generate handle return 'user123'; }, } }); ``` ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `allowDisposableEmails?` | `boolean` | When `true`, the built-in disposable-email check is skipped during signup. Defaults to `false` (built-in check enforced). Set this to `true` when you want to enforce your own domain-policy logic via [onBeforeSignup](/api-reference/modelence/server/type-aliases/AuthConfig#onbeforesignup) — for example, a service that classifies domains as public/disposable/custom with its own data sources and cache. Skipping the built-in check without registering an `onBeforeSignup` hook means disposable emails will be allowed to sign up. | [packages/modelence/src/app/authConfig.ts:454](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L454) | | ~~`errorComponent?`~~ | (`props`) => `string` \| `null` \| `undefined` | Customizes how OAuth authentication errors are rendered. By default, OAuth errors are returned as JSON; providing this returns a custom HTML response instead, which is useful when the OAuth flow runs in a browser context. Receives `{ error, statusCode }` and returns an HTML string (or `null`/`undefined` to fall back to the default JSON response). Always escape interpolated values to prevent XSS. **Deprecated** Use [AuthConfig.oauthErrorRedirectUrl](/api-reference/modelence/server/type-aliases/AuthConfig#oautherrorredirecturl) instead. It sends the browser back into the app, where the error can be shown on a real page with the app's own UI; this only ever renders a standalone document at the callback URL. Ignored when `oauthErrorRedirectUrl` is set. | [packages/modelence/src/app/authConfig.ts:401](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L401) | | `generateHandle?` | (`props`) => `Promise`\<`string`> \| `string` | Custom handle generator. If provided, overrides the default behavior (which derives the handle from the email local-part). Receives `{ email, firstName?, lastName? }` and returns the desired handle synchronously or as a `Promise`. The returned handle must contain only letters, numbers, underscores, and hyphens (matching `HANDLE_REGEX`). If the returned handle collides with an existing one, Modelence appends a numeric suffix automatically. | [packages/modelence/src/app/authConfig.ts:346](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L346) | | ~~`login?`~~ | [`AuthOption`](/api-reference/modelence/server/type-aliases/AuthOption) | **Deprecated** Use [AuthConfig.onAfterLogin](/api-reference/modelence/server/type-aliases/AuthConfig#onafterlogin) and [AuthConfig.onLoginError](/api-reference/modelence/server/type-aliases/AuthConfig#onloginerror) instead. | [packages/modelence/src/app/authConfig.ts:349](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L349) | | `magicLink?` | `object` | Enables passwordless magic link authentication. Disabled by default. Requires an email provider and delivery settings under the `email` option (see `EmailConfig.magicLink`). **Example** `startApp({ auth: { magicLink: { enabled: true, allowSignup: true }, }, });` | [packages/modelence/src/app/authConfig.ts:368](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L368) | | `magicLink.allowSignup?` | `boolean` | Allows a magic link (or its one-time code) to create an account when the email has no existing one — combined sign-in/sign-up, like OAuth. Disabled by default: unknown emails get the same generic "link sent" response but no email, and no account is ever auto-created. | [packages/modelence/src/app/authConfig.ts:376](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L376) | | `magicLink.enabled?` | `boolean` | - | [packages/modelence/src/app/authConfig.ts:369](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L369) | | `mobile?` | `object` | Settings for authenticating from a native (React Native / Expo) client. **Example** `startApp({ auth: { mobile: { redirectUrls: ['myapp://auth'] }, }, });` | [packages/modelence/src/app/authConfig.ts:468](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L468) | | `mobile.redirectUrls?` | `string`\[] | Deep links the OAuth callback is allowed to redirect a native app back to, e.g. `['myapp://auth']`. A sign-in request naming any other target is rejected before the user ever reaches the provider's consent screen. This is an allowlist because the redirect target decides where an auth flow ends up: without it, a crafted link could point the callback at an attacker-controlled destination. There is no implicit default — mobile OAuth stays disabled until at least one entry is configured here or via the `auth.mobile.redirectUrls` config value (the two are merged). Entries are matched on scheme, host and path; a request may add query parameters but may not change any of those three. | [packages/modelence/src/app/authConfig.ts:483](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L483) | | `oauthAccountLinking?` | `"auto"` \| `"manual"` | Controls how OAuth providers handle existing accounts with matching email. - 'manual' (default): Returns an error when an OAuth login matches an existing email. - 'auto': Automatically links the OAuth provider to the existing account if the provider email is verified. | [packages/modelence/src/app/authConfig.ts:385](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L385) | | `oauthErrorRedirectUrl?` | `string` | Where a failed web OAuth flow sends the browser. A path (`'/login'`), resolved against `_system.site.url`, or an absolute URL. The failure is appended as `?error=&errorCode=`, the same contract a mobile flow delivers on its deep link, so the app can show the message on a real page instead of the raw callback response. OAuth errors surface at the provider callback URL, outside any client bundle, so nothing there can render app UI. Without this (or [AuthConfig.errorComponent](/api-reference/modelence/server/type-aliases/AuthConfig#errorcomponent)) the user lands on a JSON body with no way back. When both are set, the redirect wins and `errorComponent` is not called. `error` is for display and its wording may change; branch on `errorCode`. Applies to the provider callback only. A request rejected at the sign-in *initiation* endpoint (auth not configured, a disallowed mobile `redirectUri`, a missing `codeChallenge`) still answers the calling client with JSON, since nothing has left for the provider yet. **Example** `startApp({ auth: { oauthErrorRedirectUrl: '/login', }, });` | [packages/modelence/src/app/authConfig.ts:432](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L432) | | `onAfterEmailVerification?` | (`props`) => `void` \| `Promise`\<`void`> | Fires after a user's email is successfully verified (via the verification link or implicitly via password reset). Receives `{ provider, user, session, connectionInfo }`. | [packages/modelence/src/app/authConfig.ts:316](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L316) | | `onAfterLogin?` | (`props`) => `void` \| `Promise`\<`void`> | Fires after a successful login (email/password or OAuth) once the session has been linked to the user. Receives `{ provider, user, session, connectionInfo }`. Use for analytics, audit logging, or post-login side effects. | [packages/modelence/src/app/authConfig.ts:272](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L272) | | `onAfterOAuthLink?` | (`props`) => `void` \| `Promise`\<`void`> | Fires after an OAuth provider is linked to an existing account (either automatically when `oauthAccountLinking: 'auto'` or via an explicit link flow). Receives `{ provider, user, session, connectionInfo }`. | [packages/modelence/src/app/authConfig.ts:329](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L329) | | `onAfterSignup?` | (`props`) => `void` \| `Promise`\<`void`> | Fires after a successful signup once the user record is created and the session is linked. Receives `{ provider, user, session, connectionInfo }`. Common uses: send welcome email, create default workspace, track activation. | [packages/modelence/src/app/authConfig.ts:303](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L303) | | `onBeforeSignup?` | (`props`) => `void` \| `Promise`\<`void`> | Hook fired after validation and the built-in disposable-email check, but before the new user document is inserted. Throwing aborts the signup — the thrown error is re-thrown to the caller and `onSignupError` fires. Use this to plug in a custom domain-policy check (e.g. a tenant-specific email-domain verification service) without having to disable the built-in disposable-email check. Invoked for every provider, OAuth included, so it can gate who may sign up. The built-in disposable-email check still skips OAuth signups: check `provider` to keep a disposable-domain policy to email signups, since OAuth providers (Google, GitHub, etc.) do not issue disposable accounts. Only signups reach this hook. An existing account signing in does not. | [packages/modelence/src/app/authConfig.ts:296](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L296) | | `onEmailVerificationError?` | (`props`) => `void` \| `Promise`\<`void`> | Fires when email verification fails (invalid or expired token). Receives `{ provider, error, session, connectionInfo }`. | [packages/modelence/src/app/authConfig.ts:322](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L322) | | `onLoginError?` | (`props`) => `void` \| `Promise`\<`void`> | Fires when a login attempt fails. Receives `{ provider, error, session, connectionInfo }`. Use for failure analytics or alerting — does NOT change the response sent to the client. | [packages/modelence/src/app/authConfig.ts:278](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L278) | | `onOAuthLinkError?` | (`props`) => `void` \| `Promise`\<`void`> | Fires when OAuth account linking fails. Receives `{ provider, error, session, connectionInfo }`. | [packages/modelence/src/app/authConfig.ts:335](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L335) | | `onSignupError?` | (`props`) => `void` \| `Promise`\<`void`> | Fires when a signup attempt fails (validation, duplicate email, etc.). Receives `{ provider, error, session, connectionInfo }`. Use for failure analytics — does NOT change the response sent to the client. | [packages/modelence/src/app/authConfig.ts:310](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L310) | | `rateLimits?` | [`AuthRateLimitsConfig`](/api-reference/modelence/server/type-aliases/AuthRateLimitsConfig) | Overrides the built-in rate limits for authentication endpoints. Each rule you provide is merged into the defaults by `(bucket, type, window)`: matching tuples replace the default `limit`, new tuples are added, and unspecified defaults are preserved. See [AuthRateLimitsConfig](/api-reference/modelence/server/type-aliases/AuthRateLimitsConfig) for full semantics and examples. | [packages/modelence/src/app/authConfig.ts:441](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L441) | | ~~`signup?`~~ | [`AuthOption`](/api-reference/modelence/server/type-aliases/AuthOption) | **Deprecated** Use [AuthConfig.onAfterSignup](/api-reference/modelence/server/type-aliases/AuthConfig#onaftersignup) and [AuthConfig.onSignupError](/api-reference/modelence/server/type-aliases/AuthConfig#onsignuperror) instead. | [packages/modelence/src/app/authConfig.ts:351](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L351) | | `validatePassword?` | (`props`) => `void` \| `Promise`\<`void`> | Password policy hook. Runs on **every** path that sets a password — signup and password reset today, plus any future change-password flow — after the built-in length checks (`MIN_PASSWORD_LENGTH`..`MAX_PASSWORD_LENGTH`) and before the password is hashed. Throw to reject the password; the thrown message is surfaced to the client. Prefer this over [AuthConfig.validateSignup](/api-reference/modelence/server/type-aliases/AuthConfig#validatesignup) for password rules. `validateSignup` only runs at signup, so a policy enforced there alone can be bypassed by signing up with a compliant password and immediately resetting to a weaker one. Receives `{ password, email, context }`, where `context` is the flow that triggered the check (`'signup'` or `'reset'`). May be async. **Example** `startApp({ auth: { validatePassword: ({ password }) => { if (password.length < 12) { throw new Error('Password must be at least 12 characters'); } }, }, });` | [packages/modelence/src/app/authConfig.ts:257](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L257) | | `validateProfileUpdate?` | (`props`) => `void` \| `Promise`\<`void`> | Pre-update validation hook. Runs before a user's profile fields (`firstName`, `lastName`, `avatarUrl`, `handle`) are written. Throw to reject the update — the thrown message is surfaced to the client. May be async. | [packages/modelence/src/app/authConfig.ts:265](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L265) | | `validateSignup?` | (`props`) => `void` \| `Promise`\<`void`> | Pre-signup validation hook. Runs before a new user is created during email/password signup, after format checks but before duplicate detection. Throw to reject the signup — the thrown message is surfaced to the client. Receives the raw signup payload (`email`, `password`, and optional `firstName`, `lastName`, `avatarUrl`, `handle`). May be async. | [packages/modelence/src/app/authConfig.ts:227](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L227) | # AuthOption Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/AuthOption [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / AuthOption > **AuthOption** = `object` Defined in: [packages/modelence/src/app/authConfig.ts:162](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L162) Callback options for authentication operations ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `onError?` | (`error`) => `void` \| `Promise`\<`void`> | Callback executed when authentication fails | [packages/modelence/src/app/authConfig.ts:166](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L166) | | `onSuccess?` | (`user`) => `void` \| `Promise`\<`void`> | Callback executed when authentication succeeds | [packages/modelence/src/app/authConfig.ts:164](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L164) | # AuthRateLimitOverride Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/AuthRateLimitOverride [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / AuthRateLimitOverride > **AuthRateLimitOverride** = `object` Defined in: [packages/modelence/src/app/authConfig.ts:21](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L21) A single rate-limit rule for an authentication bucket. The `bucket` is implied by which auth action you're configuring (e.g. `signup`), so callers only specify the actor type, window size, and limit. ## Example ```typescript theme={null} import { time } from 'modelence'; const rule: AuthRateLimitOverride = { type: 'ip', window: time.minutes(15), limit: 10, }; ``` ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `limit` | `number` | Maximum allowed hits within the window. | [packages/modelence/src/app/authConfig.ts:27](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L27) | | `type` | [`RateLimitType`](/api-reference/modelence/server/type-aliases/RateLimitType) | Identifier type of the actor this rule applies to. | [packages/modelence/src/app/authConfig.ts:23](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L23) | | `window` | `number` | Time window size in milliseconds. Use `time.minutes(15)` etc. | [packages/modelence/src/app/authConfig.ts:25](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L25) | # AuthRateLimitsConfig Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/AuthRateLimitsConfig [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / AuthRateLimitsConfig > **AuthRateLimitsConfig** = `object` Defined in: [packages/modelence/src/app/authConfig.ts:73](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L73) Per-action rate limit overrides for authentication endpoints. Each bucket accepts an array of rules that are merged into the built-in defaults by `(type, window)` tuple: * A rule whose `(type, window)` matches a default replaces that default's `limit`. * A rule whose `(type, window)` does not match any default is added as an extra rule for the bucket. * Defaults whose `(type, window)` is not overridden are kept. This means you can tighten a single window without accidentally dropping the other built-in protections for that bucket. ## Examples ```typescript theme={null} import { startApp } from 'modelence/server'; import { time } from 'modelence'; startApp({ auth: { rateLimits: { signup: [ { type: 'ip', window: time.minutes(15), limit: 5 }, ], }, }, }); ``` ```typescript theme={null} startApp({ auth: { rateLimits: { signup: [ { type: 'ip', window: time.minutes(1), limit: 2 }, ], }, }, }); ``` ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `magicLink?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Rate limits for magic link requests. | [packages/modelence/src/app/authConfig.ts:89](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L89) | | `oauthExchange?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Rate limits for redeeming a mobile OAuth exchange code. | [packages/modelence/src/app/authConfig.ts:93](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L93) | | `oneTimeCode?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Rate limits for one-time code sign-in attempts. | [packages/modelence/src/app/authConfig.ts:91](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L91) | | `passwordReset?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Rate limits for password reset requests. | [packages/modelence/src/app/authConfig.ts:87](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L87) | | `signin?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Per-IP and per-email limits for login attempts. The email bucket only counts failed attempts, and blocks every attempt (even with the correct password) once it is full. | [packages/modelence/src/app/authConfig.ts:83](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L83) | | `signup?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Per-IP limits for the signup endpoint (successful signups only). | [packages/modelence/src/app/authConfig.ts:75](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L75) | | `signupAttempt?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Per-IP limits for signup attempts (checked before duplicate detection). | [packages/modelence/src/app/authConfig.ts:77](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L77) | | `updateProfile?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Per-user rate limits for profile updates. | [packages/modelence/src/app/authConfig.ts:95](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L95) | | `verification?` | [`AuthRateLimitOverride`](/api-reference/modelence/server/type-aliases/AuthRateLimitOverride)\[] | Per-user and per-IP limits for email verification resend requests. | [packages/modelence/src/app/authConfig.ts:85](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/authConfig.ts#L85) | # CloudBackendConnectResponse Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/CloudBackendConnectResponse [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / CloudBackendConnectResponse > **CloudBackendConnectResponse** = `CloudBackendConnectOkResponse` | `CloudBackendConnectErrorResponse` Defined in: [packages/modelence/src/app/backendApi.ts:29](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/backendApi.ts#L29) # ConfigType Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/ConfigType [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / ConfigType > **ConfigType** = `"text"` | `"string"` | `"number"` | `"boolean"` | `"secret"` Defined in: [packages/modelence/src/config/types.ts:10](https://github.com/modelence/modelence/blob/main/packages/modelence/src/config/types.ts#L10) The available types for module configuration values. * `'string'` — A short text value (single line) * `'text'` — A longer text value (multi-line) * `'number'` — A numeric value * `'boolean'` — A true/false toggle * `'secret'` — A sensitive string value (e.g. API keys, tokens). Masked in the Cloud dashboard and cannot be marked as `isPublic`. # CronJobInputParams Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/CronJobInputParams [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / CronJobInputParams > **CronJobInputParams** = `object` Defined in: [packages/modelence/src/cron/types.ts:19](https://github.com/modelence/modelence/blob/main/packages/modelence/src/cron/types.ts#L19) ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `description?` | `string` | - | [packages/modelence/src/cron/types.ts:20](https://github.com/modelence/modelence/blob/main/packages/modelence/src/cron/types.ts#L20) | | `handler` | `CronJobHandler` | - | [packages/modelence/src/cron/types.ts:31](https://github.com/modelence/modelence/blob/main/packages/modelence/src/cron/types.ts#L31) | | `interval` | `number` | - | [packages/modelence/src/cron/types.ts:21](https://github.com/modelence/modelence/blob/main/packages/modelence/src/cron/types.ts#L21) | | `timeout?` | `number` | How long a run may take, in milliseconds, before an error is reported. The error repeats every `timeout` until the run finishes. This only reports: nothing aborts the handler, and the job won't run again until it settles. A handler that never settles blocks its job until the process restarts, so give any network or database calls in it their own timeouts. | [packages/modelence/src/cron/types.ts:30](https://github.com/modelence/modelence/blob/main/packages/modelence/src/cron/types.ts#L30) | # FileVisibility Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/FileVisibility [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / FileVisibility > **FileVisibility** = `"public"` | `"private"` Defined in: [packages/modelence/src/files/types.ts:1](https://github.com/modelence/modelence/blob/main/packages/modelence/src/files/types.ts#L1) # HstsConfig Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/HstsConfig [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / HstsConfig > **HstsConfig** = `object` Defined in: [packages/modelence/src/app/securityHeaders.ts:15](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityHeaders.ts#L15) Options for the `Strict-Transport-Security` header. ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `includeSubDomains?` | `boolean` | Apply the policy to every subdomain as well. Defaults to `false`. | [packages/modelence/src/app/securityHeaders.ts:19](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityHeaders.ts#L19) | | `maxAge?` | `number` | Seconds the browser should remember to use HTTPS only. Defaults to one year. | [packages/modelence/src/app/securityHeaders.ts:17](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityHeaders.ts#L17) | | `preload?` | `boolean` | Signal consent to inclusion in browsers' HSTS preload list. Requires `includeSubDomains` and a `maxAge` of at least one year. | [packages/modelence/src/app/securityHeaders.ts:24](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityHeaders.ts#L24) | # HttpMethod Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/HttpMethod [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / HttpMethod > **HttpMethod** = `"get"` | `"post"` | `"put"` | `"delete"` | `"patch"` | `"options"` | `"head"` | `"all"` | `"use"` Defined in: [packages/modelence/src/routes/types.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L4) # LiveQueryCleanup Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/LiveQueryCleanup [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / LiveQueryCleanup > **LiveQueryCleanup** = () => `void` Defined in: [packages/modelence/src/live-query/context.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L11) Cleanup function returned by watch handlers. Called when the client unsubscribes. ## Returns `void` # LiveQueryPublish Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/LiveQueryPublish [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / LiveQueryPublish > **LiveQueryPublish** = () => `void` Defined in: [packages/modelence/src/live-query/context.ts:5](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L5) Publish function provided to watch handlers. Call this to trigger a re-fetch and send updated data to the client. ## Returns `void` # LiveQueryWatch Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/LiveQueryWatch [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / LiveQueryWatch > **LiveQueryWatch** = (`context`) => [`LiveQueryCleanup`](/api-reference/modelence/server/type-aliases/LiveQueryCleanup) | `void` Defined in: [packages/modelence/src/live-query/context.ts:25](https://github.com/modelence/modelence/blob/main/packages/modelence/src/live-query/context.ts#L25) Watch function that sets up real-time monitoring. Receives a context with publish callback to trigger re-fetches. Returns a cleanup function. ## Parameters | Parameter | Type | | - | - | | `context` | `WatchContext` | ## Returns [`LiveQueryCleanup`](/api-reference/modelence/server/type-aliases/LiveQueryCleanup) | `void` # RateLimitRule Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RateLimitRule [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RateLimitRule > **RateLimitRule** = `object` Defined in: [packages/modelence/src/rate-limit/types.ts:3](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/types.ts#L3) ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `bucket` | `string` | Logical action being limited, e.g. "signup" | [packages/modelence/src/rate-limit/types.ts:5](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/types.ts#L5) | | `limit` | `number` | Maximum allowed hits within the window | [packages/modelence/src/rate-limit/types.ts:14](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/types.ts#L14) | | `type` | [`RateLimitType`](/api-reference/modelence/server/type-aliases/RateLimitType) | Identifier type of the actor this rule applies to | [packages/modelence/src/rate-limit/types.ts:8](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/types.ts#L8) | | `window` | `number` | Time window size in milliseconds | [packages/modelence/src/rate-limit/types.ts:11](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/types.ts#L11) | # RateLimitType Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RateLimitType [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RateLimitType > **RateLimitType** = `"ip"` | `"user"` | `"email"` Defined in: [packages/modelence/src/rate-limit/types.ts:1](https://github.com/modelence/modelence/blob/main/packages/modelence/src/rate-limit/types.ts#L1) # ReferrerPolicy Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/ReferrerPolicy [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / ReferrerPolicy > **ReferrerPolicy** = `"no-referrer"` | `"no-referrer-when-downgrade"` | `"origin"` | `"origin-when-cross-origin"` | `"same-origin"` | `"strict-origin"` | `"strict-origin-when-cross-origin"` | `"unsafe-url"` Defined in: [packages/modelence/src/app/securityHeaders.ts:4](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityHeaders.ts#L4) Values accepted by the `Referrer-Policy` header. # RoleDefinition Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RoleDefinition [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RoleDefinition > **RoleDefinition** = `object` Defined in: [packages/modelence/src/auth/types.ts:88](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L88) Defines a role that can be assigned to users. Roles are registered via the `roles` option in [AppOptions](/api-reference/modelence/server/type-aliases/AppOptions) and are synced to the Modelence Cloud dashboard for user management. ## Example ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ roles: { admin: { description: 'Full access to all features' }, editor: { description: 'Can edit content' }, viewer: {}, }, }); ``` ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `description?` | `string` | Human-readable description of the role, shown in the Modelence Cloud dashboard. | [packages/modelence/src/auth/types.ts:90](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L90) | # RouteDefinition Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RouteDefinition [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RouteDefinition > **RouteDefinition** = `object` Defined in: [packages/modelence/src/routes/types.ts:68](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L68) ## Properties | Property | Type | Defined in | | - | - | - | | `body?` | `BodyConfig` | [packages/modelence/src/routes/types.ts:72](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L72) | | `errorHandler?` | [`RouteHandler`](/api-reference/modelence/server/type-aliases/RouteHandler) | [packages/modelence/src/routes/types.ts:71](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L71) | | `handlers` | `RouteHandlers` | [packages/modelence/src/routes/types.ts:70](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L70) | | `path` | `string` | [packages/modelence/src/routes/types.ts:69](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L69) | # RouteHandler Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RouteHandler [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RouteHandler > **RouteHandler**\<`T`> = (`params`, `context`) => `Promise`\<[`RouteResponse`](/api-reference/modelence/server/type-aliases/RouteResponse)\<`T`>> | [`RouteResponse`](/api-reference/modelence/server/type-aliases/RouteResponse)\<`T`> Defined in: [packages/modelence/src/routes/types.ts:39](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L39) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Parameters | Parameter | Type | | - | - | | `params` | [`RouteParams`](/api-reference/modelence/server/type-aliases/RouteParams) | | `context` | `Pick`\<`Context`, `"session"` \| `"user"`> | ## Returns `Promise`\<[`RouteResponse`](/api-reference/modelence/server/type-aliases/RouteResponse)\<`T`>> | [`RouteResponse`](/api-reference/modelence/server/type-aliases/RouteResponse)\<`T`> # RouteParams Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RouteParams [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RouteParams > **RouteParams**\<`T`> = `object` Defined in: [packages/modelence/src/routes/types.ts:15](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L15) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Properties | Property | Type | Defined in | | - | - | - | | `body` | `T` | [packages/modelence/src/routes/types.ts:17](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L17) | | `cookies` | `Record`\<`string`, `string`> | [packages/modelence/src/routes/types.ts:20](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L20) | | `headers` | `Record`\<`string`, `string`> | [packages/modelence/src/routes/types.ts:19](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L19) | | `next` | `NextFunction` | [packages/modelence/src/routes/types.ts:24](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L24) | | `params` | `Record`\<`string`, `string`> | [packages/modelence/src/routes/types.ts:18](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L18) | | `query` | `Record`\<`string`, `string`> | [packages/modelence/src/routes/types.ts:16](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L16) | | `rawBody?` | `Buffer` | [packages/modelence/src/routes/types.ts:21](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L21) | | `req` | `Request` | [packages/modelence/src/routes/types.ts:22](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L22) | | `res` | `Response` | [packages/modelence/src/routes/types.ts:23](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L23) | # RouteResponse Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/RouteResponse [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / RouteResponse > **RouteResponse**\<`T`> = \{ `contentType?`: `string`; `data?`: `T`; `headers?`: `Record`\<`string`, `string`>; `redirect?`: `string`; `status?`: `number`; } | `null` Defined in: [packages/modelence/src/routes/types.ts:27](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L27) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` | `unknown` | ## Type declaration \{ `contentType?`: `string`; `data?`: `T`; `headers?`: `Record`\<`string`, `string`>; `redirect?`: `string`; `status?`: `number`; } | Name | Type | Description | Defined in | | - | - | - | - | | `contentType?` | `string` | Sets the response Content-Type before sending `data`. A Content-Type supplied through `headers` takes precedence when both options are provided. | [packages/modelence/src/routes/types.ts:35](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L35) | | `data?` | `T` | - | [packages/modelence/src/routes/types.ts:28](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L28) | | `headers?` | `Record`\<`string`, `string`> | - | [packages/modelence/src/routes/types.ts:30](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L30) | | `redirect?` | `string` | - | [packages/modelence/src/routes/types.ts:36](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L36) | | `status?` | `number` | - | [packages/modelence/src/routes/types.ts:29](https://github.com/modelence/modelence/blob/main/packages/modelence/src/routes/types.ts#L29) | `null` # SecurityConfig Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/SecurityConfig [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / SecurityConfig > **SecurityConfig** = `object` Defined in: [packages/modelence/src/app/securityConfig.ts:59](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L59) Security configuration for the application By default, every response carries: * `Content-Security-Policy: frame-ancestors 'self'` and `X-Frame-Options: SAMEORIGIN`, preventing the app from being embedded in iframes on other domains * `X-Content-Type-Options: nosniff` * `Referrer-Policy: strict-origin-when-cross-origin` `script-src` and `Strict-Transport-Security` are opt-in. ## Examples ```typescript theme={null} import { startApp } from 'modelence/server'; // Allow embedding in iframes on specific domains startApp({ security: { frameAncestors: ['https://modelence.com', 'https://app.example.com'], trustedProxies: ['loopback', 'linklocal', 'uniquelocal'], clientIpHeader: 'cf-connecting-ip', }, }); ``` ```typescript theme={null} // Only run scripts served by the app itself or by Stripe, and require HTTPS startApp({ security: { scriptSrc: ['https://js.stripe.com'], hsts: { maxAge: 31536000, includeSubDomains: true }, referrerPolicy: 'same-origin', }, }); ``` ```typescript theme={null} // Allow a browser client on another origin to call this app's API (e.g. Expo // Web, which Metro serves on :8081 while the API runs on :3000). Applies to // module routes and framework API routes, not to SSR pages or static assets. startApp({ security: { allowedOrigins: ['http://localhost:8081'], }, }); ``` ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `allowedOrigins?` | `string`\[] | Origins allowed to read this app's responses from a browser (CORS). Browsers block a cross-origin `fetch` unless the response carries a matching `Access-Control-Allow-Origin`. The common case is Expo Web, which Metro serves on a different port from the API — a different port is a different origin, so every method call is blocked without this. Scope: this covers your module routes and the framework's own API routes (method calls and the OAuth endpoints). SSR pages and static assets are excluded, so a listed origin can call your API but cannot read your rendered pages with credentials. The scope is derived from the routes actually registered, not matched by path prefix: module routes carry no framework-imposed prefix (the docs' example mounts `/todos` at the root), so a prefix rule would silently drop CORS from the user-defined routes that most need it. Each entry must be an exact origin (`scheme://host[:port]`); patterns and wildcards are not supported, since the response header carries one concrete origin. Entries are normalized (trimmed, lowercased, default port and trailing slash dropped) to match what browsers send, and anything that is not a valid origin throws at startup rather than silently never matching. The matched origin is echoed back rather than `*`, and `Access-Control-Allow-Credentials` is sent, so the browser will expose a credentialed response to JS. Note this only covers same-site requests: the auth cookie is `SameSite=Lax`, so a genuinely cross-site caller (`app.example.com` → `api.other.com`) never has the cookie attached in the first place, regardless of this setting. The Expo Web case works because `localhost:8081` and `localhost:3000` differ only by port, and port is not part of a site. Listed origins are also the only foreign origins allowed to call methods and the OAuth linking endpoints from a browser. Those routes act as the signed-in user, so a browser request to them from any other origin — including a sibling subdomain of the same site — is rejected with 403. List only origins you trust to act on behalf of your users. Opt-in by design: when unset, no CORS headers are sent at all. Deployments that already add CORS at a proxy or router therefore stay untouched — a duplicated `Access-Control-Allow-Origin` is invalid and would break them. Native iOS/Android do not enforce CORS and never need this. | [packages/modelence/src/app/securityConfig.ts:163](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L163) | | `clientIpHeader?` | `string` | Name of a single-value header the trusted proxy sets to the originating client IP, used instead of walking the `X-Forwarded-For` chain. Cloudflare recommends reading `CF-Connecting-IP` (or `True-Client-IP` on Enterprise plans) rather than `X-Forwarded-For`, because Cloudflare *appends* to an inbound `X-Forwarded-For` instead of overwriting it, while these headers always carry exactly one address. This header is only read when the immediate peer is a trusted proxy, so `trustedProxies` (or `MODELENCE_TRUSTED_PROXIES`) must also be configured with the proxy's addresses. Without that, a direct caller could set the header themselves and choose their own rate-limit identity. When the peer is untrusted or the header is absent, the IP falls back to the normal `trust proxy` resolution. **Example** `// Behind Cloudflare, with Cloudflare's published ranges trusted: clientIpHeader: 'cf-connecting-ip'` | [packages/modelence/src/app/securityConfig.ts:209](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L209) | | `frameAncestors?` | `string`\[] | Additional origins allowed to embed this app in an iframe. The app's own origin (`'self'`) is always included automatically. When not set, only same-origin framing is allowed. When set, `X-Frame-Options` is omitted since it cannot express multiple origins. | [packages/modelence/src/app/securityConfig.ts:67](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L67) | | `hsts?` | `boolean` \| [`HstsConfig`](/api-reference/modelence/server/type-aliases/HstsConfig) | Sends `Strict-Transport-Security`, telling browsers to reach this host over HTTPS only. `true` uses `max-age=31536000` (one year) without subdomains; pass an object to tune it. Off by default: browsers cache the policy for `maxAge`, so enabling it on a host that still needs plain HTTP (or `includeSubDomains` on a domain with HTTP-only subdomains) is hard to undo. Browsers ignore the header on plain-HTTP responses, so it is safe to leave on in local development. | [packages/modelence/src/app/securityConfig.ts:103](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L103) | | `noSniff?` | `boolean` | Sends `X-Content-Type-Options: nosniff`, so browsers refuse to run a response as a script or stylesheet unless its `Content-Type` says so. Defaults to `true`; set `false` to omit the header. | [packages/modelence/src/app/securityConfig.ts:117](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L117) | | `referrerPolicy?` | [`ReferrerPolicy`](/api-reference/modelence/server/type-aliases/ReferrerPolicy) \| `false` | Value of the `Referrer-Policy` header. Defaults to `'strict-origin-when-cross-origin'`, which sends only the origin to other sites and nothing on HTTPS→HTTP navigations. Set `false` to omit the header. | [packages/modelence/src/app/securityConfig.ts:110](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L110) | | `scriptSrc?` | `string`\[] | Sources allowed to load scripts, sent as the CSP `script-src` directive. The app's own origin (`'self'`) is always included automatically, so an empty list yields `script-src 'self'` — the strictest policy that still runs the app's bundle. When not set, no `script-src` directive is sent and scripts are unrestricted. Setting it is the main defence against injected scripts reading the session token, which the client keeps in `localStorage`. Each entry is a single CSP source: a host (`https://js.stripe.com`), a scheme (`https:`), or a single-quoted keyword or hash (`'unsafe-eval'`, `'sha256-...'`). Unquoted or unrecognised keywords, `*`, `'none'`, `'strict-dynamic'`, static nonces, and entries holding more than one source throw at startup. Inline scripts in `index.html` (analytics snippets, theme bootstrapping) are blocked unless allowed by hash. Outside production (`NODE_ENV !== 'production'`), `'unsafe-inline'` is added (and hashes dropped, since they would disable it) so the Vite dev server's inline React Refresh preamble can run; test the policy against a production build. | [packages/modelence/src/app/securityConfig.ts:91](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L91) | | `trustedProxies?` | `string` \| `string`\[] | IP addresses or CIDR ranges of reverse proxies that are allowed to supply the client IP through `X-Forwarded-For`. This uses Express's `trust proxy` address syntax, which also supports the named ranges `loopback`, `linklocal`, and `uniquelocal`. For backward compatibility, all proxy addresses are trusted when neither this option nor `MODELENCE_TRUSTED_PROXIES` is set. Configure one of them in production so only addresses that cannot be reached directly by untrusted clients are trusted. Once configured, `connectionInfo.ip` is resolved by walking the proxy chain from the app toward the client and stopping at the first untrusted address. This keeps a caller from choosing its rate-limit identity by prepending a forged `X-Forwarded-For` value. **Example** `trustedProxies: ['loopback', '10.0.0.0/8']` | [packages/modelence/src/app/securityConfig.ts:185](https://github.com/modelence/modelence/blob/main/packages/modelence/src/app/securityConfig.ts#L185) | # UserInfo Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/UserInfo [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / UserInfo > **UserInfo** = `object` Defined in: [packages/modelence/src/auth/types.ts:41](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L41) ## Properties | Property | Type | Description | Defined in | | - | - | - | - | | `avatarUrl?` | `string` | - | [packages/modelence/src/auth/types.ts:54](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L54) | | `firstName?` | `string` | - | [packages/modelence/src/auth/types.ts:52](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L52) | | `handle` | `string` | The user's display handle. | [packages/modelence/src/auth/types.ts:45](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L45) | | `hasRole` | (`role`) => `boolean` | Returns `true` if the user has the given role. | [packages/modelence/src/auth/types.ts:49](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L49) | | `id` | `string` | The user's unique identifier. | [packages/modelence/src/auth/types.ts:43](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L43) | | `lastName?` | `string` | - | [packages/modelence/src/auth/types.ts:53](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L53) | | `requireRole` | (`role`) => `void` | Throws an error if the user does not have the given role. | [packages/modelence/src/auth/types.ts:51](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L51) | | `roles` | `string`\[] | The role strings assigned to this user in the database. | [packages/modelence/src/auth/types.ts:47](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/types.ts#L47) | # ValueType Source: https://docs.modelence.com/api-reference/modelence/server/type-aliases/ValueType [API Reference](/api-reference/modelence/server/type-aliases/../../../index) / [modelence](/api-reference/modelence/server/type-aliases/../../index) / [server](/api-reference/modelence/server/type-aliases/../index) / ValueType > **ValueType**\<`T`> = `T` *extends* `"number"` ? `number` : `T` *extends* `"string"` ? `string` : `T` *extends* `"text"` ? `string` : `T` *extends* `"boolean"` ? `boolean` : `T` *extends* `"secret"` ? `string` : `never` Defined in: [packages/modelence/src/config/types.ts:14](https://github.com/modelence/modelence/blob/main/packages/modelence/src/config/types.ts#L14) ## Type Parameters | Type Parameter | Default type | | - | - | | `T` *extends* [`ConfigType`](/api-reference/modelence/server/type-aliases/ConfigType) | [`ConfigType`](/api-reference/modelence/server/type-aliases/ConfigType) | # dbSessions Source: https://docs.modelence.com/api-reference/modelence/server/variables/dbSessions [API Reference](/api-reference/modelence/server/variables/../../../index) / [modelence](/api-reference/modelence/server/variables/../../index) / [server](/api-reference/modelence/server/variables/../index) / dbSessions > `const` **dbSessions**: [`Store`](/api-reference/modelence/server/variables/../classes/Store)\<\{ `authToken`: `ZodString`; `createdAt`: `ZodDate`; `expiresAt`: `ZodDate`; `lastActiveDate`: `ZodOptional`\<`ZodDate`>; `userId`: `ZodNullable`\<`ZodType`\<`ObjectId`, `ZodTypeDef`, `ObjectId`>>; }, `Record`\<`string`, (`this`, ...`args`) => `any`>> Defined in: [packages/modelence/src/auth/session.ts:143](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/session.ts#L143) # dbUsers Source: https://docs.modelence.com/api-reference/modelence/server/variables/dbUsers [API Reference](/api-reference/modelence/server/variables/../../../index) / [modelence](/api-reference/modelence/server/variables/../../index) / [server](/api-reference/modelence/server/variables/../index) / dbUsers > `const` **dbUsers**: [`Store`](/api-reference/modelence/server/variables/../classes/Store)\<\{ `authMethods`: `ZodObject`\<\{ `github`: `ZodOptional`\<`ZodObject`\<\{ `id`: `ZodString`; }, `"strip"`, `ZodTypeAny`, \{ `id`: `string`; }, \{ `id`: `string`; }>>; `google`: `ZodOptional`\<`ZodObject`\<\{ `id`: `ZodString`; }, `"strip"`, `ZodTypeAny`, \{ `id`: `string`; }, \{ `id`: `string`; }>>; `password`: `ZodOptional`\<`ZodObject`\<\{ `hash`: `ZodString`; }, `"strip"`, `ZodTypeAny`, \{ `hash`: `string`; }, \{ `hash`: `string`; }>>; }, `"strip"`, `ZodTypeAny`, \{ `github?`: \{ `id`: `string`; }; `google?`: \{ `id`: `string`; }; `password?`: \{ `hash`: `string`; }; }, \{ `github?`: \{ `id`: `string`; }; `google?`: \{ `id`: `string`; }; `password?`: \{ `hash`: `string`; }; }>; `avatarUrl`: `ZodOptional`\<`ZodString`>; `createdAt`: `ZodDate`; `deletedAt`: `ZodOptional`\<`ZodDate`>; `disabledAt`: `ZodOptional`\<`ZodDate`>; `emails`: `ZodOptional`\<`ZodArray`\<`ZodObject`\<\{ `address`: `ZodString`; `verified`: `ZodBoolean`; }, `"strip"`, `ZodTypeAny`, \{ `address`: `string`; `verified`: `boolean`; }, \{ `address`: `string`; `verified`: `boolean`; }>, `"many"`>>; `firstName`: `ZodOptional`\<`ZodString`>; `handle`: `ZodString`; `lastName`: `ZodOptional`\<`ZodString`>; `roles`: `ZodOptional`\<`ZodArray`\<`ZodString`, `"many"`>>; `status`: `ZodOptional`\<`ZodEnum`\<\[`"active"`, `"disabled"`, `"deleted"`]>>; }, `Record`\<`string`, (`this`, ...`args`) => `any`>> Defined in: [packages/modelence/src/auth/db.ts:18](https://github.com/modelence/modelence/blob/main/packages/modelence/src/auth/db.ts#L18) Database collection for storing user accounts with authentication methods and profile information. This is where **signupWithPassword** automatically creates new users. ## Example ```typescript theme={null} // Find user by email const user = await dbUsers.findOne( { 'emails.address': 'john@example.com' } ); ``` # schema Source: https://docs.modelence.com/api-reference/modelence/server/variables/schema [API Reference](/api-reference/modelence/server/variables/../../../index) / [modelence](/api-reference/modelence/server/variables/../../index) / [server](/api-reference/modelence/server/variables/../index) / schema > `const` **schema**: `object` Defined in: [packages/modelence/src/data/types.ts:31](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L31) ## Type declaration | Name | Type | Default value | Defined in | | - | - | - | - | | `array()` | \<`El`>(`schema`, `params?`) => `ZodArray`\<`El`> | `schemaArray` | [packages/modelence/src/data/types.ts:36](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L36) | | `boolean()` | (`params?`) => `ZodBoolean` | `schemaBoolean` | [packages/modelence/src/data/types.ts:35](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L35) | | `date()` | (`params?`) => `ZodDate` | `schemaDate` | [packages/modelence/src/data/types.ts:34](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L34) | | `enum()` | \{\<`U`, `T`>(`values`, `params?`): `ZodEnum`\<`Writeable`\<`T`>>; \<`U`, `T`>(`values`, `params?`): `ZodEnum`\<`T`>; } | `schemaEnum` | [packages/modelence/src/data/types.ts:38](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L38) | | `number()` | (`params?`) => `ZodNumber` | `schemaNumber` | [packages/modelence/src/data/types.ts:33](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L33) | | `object()` | \<`Shape`>(`shape`, `params?`) => `ZodObject`\<`Shape`, `"strip"`, `ZodTypeAny`, \{ \[k in string \| number \| symbol]: addQuestionMarks\, any>\[k] }, \{ \[k in string \| number \| symbol]: baseObjectInputType\\[k] }> | `schemaObject` | [packages/modelence/src/data/types.ts:37](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L37) | | `string()` | (`params?`) => `ZodString` | `schemaString` | [packages/modelence/src/data/types.ts:32](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L32) | | `union()` | \<`Options`>(`types`, `params?`) => `ZodUnion`\<`Options`> | - | [packages/modelence/src/data/types.ts:53](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L53) | | `embedding()` | () => `ZodArray`\<`ZodNumber`> | - | [packages/modelence/src/data/types.ts:39](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L39) | | `infer()` | (`_schema`) => `InferDocumentType`\<`T`> | - | [packages/modelence/src/data/types.ts:54](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L54) | | `objectId()` | () => `ZodType`\<`ObjectId`> | - | [packages/modelence/src/data/types.ts:42](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L42) | | `ref()` | (`_collection`) => `ZodType`\<`ObjectId`> | - | [packages/modelence/src/data/types.ts:48](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L48) | | `userId()` | () => `ZodType`\<`ObjectId`> | - | [packages/modelence/src/data/types.ts:45](https://github.com/modelence/modelence/blob/main/packages/modelence/src/data/types.ts#L45) | # Email Verification Source: https://docs.modelence.com/authentication/email-verification Email verification adds an extra layer of security by ensuring users own the email address they register with. > The email delivery setup below (provider, sender, template, redirect URL) is configured under the **`email:`** key of `startApp`. To run code when verification succeeds or fails, register the `onAfterEmailVerification` / `onEmailVerificationError` callbacks under **`auth:`** — see [Auth Hooks](/authentication/hooks). ## Enabling Email Verification First, configure your email provider (see [Email Configuration](/email)): ```typescript theme={null} import { startApp } from 'modelence/server'; import resendProvider from '@modelence/resend'; startApp({ email: { provider: resendProvider, from: 'noreply@yourdomain.com', verification: { subject: 'Verify your email', redirectUrl: 'https://yourdomain.com/email-verified', }, }, }); ``` ## How It Works 1. When a user signs up, a verification token is generated and stored 2. An email with a verification link is sent to the user's email address 3. The link contains the token: `https://yourapp.com/api/_internal/auth/verify-email?token=...` 4. When clicked, the token is validated and the user's email is marked as verified 5. The user is redirected to your configured `redirectUrl` with `?status=verified`, or `?status=error&message=...` if the link is invalid or expired Opening the link does not sign the user in, so your `redirectUrl` page should send them to sign in. Corporate mail scanners often open links before the user does. Opening a link again after it has verified the address still redirects with `status=verified`, so the user's own click succeeds. Tokens are stored hashed and expire after 24 hours. ## Custom Verification Templates You can customize the verification email template: ```typescript theme={null} startApp({ email: { provider: resendProvider, from: 'noreply@yourdomain.com', verification: { subject: 'Welcome! Please verify your email', template: ({ name, email, verificationUrl }) => `

Welcome to Our App!

Hi ${name || 'there'},

Please click the button below to verify your email address:

Verify Email

Or copy and paste this link: ${verificationUrl}

`, redirectUrl: 'https://yourdomain.com/email-verified', }, }, }); ``` ## Manual Verification You can also manually complete email verification from the client using a verification token: Manual verification confirms the email address without creating or replacing the caller's login session. It triggers the `onAfterEmailVerification` or `onEmailVerificationError` hook with `session: null` and the caller's connection information, matching the emailed-link route. The default emailed link goes to the server verification route. To use your own verification page, configure `email.verification.template` to extract the `token` from the supplied `verificationUrl` and link to your page with that token. The page should read the token from its URL and call `verifyEmail` when the user confirms. ```typescript theme={null} import { verifyEmail } from 'modelence/client'; async function handleVerification(token: string) { try { await verifyEmail({ token }); console.log('Email verified successfully!'); } catch (error) { console.error('Verification failed:', error.message); } } ``` ## Automatic Verification via Password Reset If a user resets their password and their email was not yet verified, the email is automatically marked as verified upon a successful password reset. Since the user must receive the reset email to complete the flow, this proves ownership of the address. See [Password Reset](/authentication/password-reset) for setup details. ## Resending Verification Email If the user did not receive the original verification email, you can resend it. The email is only sent when the address is registered and not yet verified — a generic response is always returned regardless, to avoid leaking account information. This endpoint enforces the following limits via the `verification` rate limit bucket: * **1 per 60 seconds** — per user, a new verification email cannot be sent until 60 seconds have passed since the previous one. * **10 per day** — per user, a maximum of 10 verification emails can be sent within a 24-hour window. * **10 per 15 minutes, 100 per day** — per IP, counted on every call whether or not the address is registered, so one client can't cycle through many addresses. ```typescript theme={null} import { resendEmailVerification } from 'modelence/client'; async function handleResend(email: string) { try { await resendEmailVerification({ email }); console.log('Verification email sent'); } catch (error) { console.error('Error:', error.message); } } ``` # GitHub Sign-In Source: https://docs.modelence.com/authentication/github-sign-in Modelence supports OAuth authentication with GitHub, allowing users to sign in with their GitHub accounts. ## Prerequisites Before implementing GitHub Sign-In, you need to: 1. Have a GitHub account 2. Register a new OAuth application on GitHub 3. Obtain OAuth credentials (Client ID and Client Secret) 4. Configure authorization callback URLs ## GitHub OAuth App Setup 1. **Create an OAuth App** * Go to [GitHub Developer Settings](https://github.com/settings/developers) * Click "OAuth Apps" in the left sidebar * Click "New OAuth App" 2. **Configure Application Details** * **Application name**: Enter your application's name * **Homepage URL**: * For local development: `http://localhost:3000` * For production: `https://yourdomain.com` * **Application description**: (Optional) Describe your application * **Authorization callback URL**: This is critical for OAuth to work * For local development: `http://localhost:3000/api/_internal/auth/github/callback` * For production: `https://yourdomain.com/api/_internal/auth/github/callback` > [!NOTE] > > GitHub allows only one callback URL per OAuth App, and that is all Modelence > needs. React Native sign-in reuses this same callback and returns to your app > through a deep link — see [React Native](/react-native#oauth-sign-in). 3. **Register Application** * Click "Register application" 4. **Generate Client Secret** * After registration, you'll see your **Client ID** * Click "Generate a new client secret" * Copy and save the **Client Secret** immediately (it won't be shown again) 5. **Save Credentials** * Store your **Client ID** and **Client Secret** securely * Use environment variables or Modelence Cloud config * Never commit these credentials to version control ## Server-Side Configuration GitHub Sign-In is built into Modelence and requires no additional packages. ### Option 1: Modelence Cloud (Recommended) The preferred way to configure GitHub authentication is through [Modelence Cloud](https://cloud.modelence.com/): 1. Go to [https://cloud.modelence.com/](https://cloud.modelence.com/) 2. Navigate to your project 3. Go to **Users → Auth Providers → GitHub** 4. Enable GitHub authentication 5. Enter your **Client ID** and **Client Secret** from GitHub 6. Save the configuration This approach allows you to manage your configuration centrally through an intuitive UI and keeps sensitive credentials secure. ### Option 2: Environment Variables Alternatively, you can use environment variables. Create a `.env` file in your project root: ```bash theme={null} MODELENCE_AUTH_GITHUB_ENABLED=true MODELENCE_AUTH_GITHUB_CLIENT_ID=your-github-client-id MODELENCE_AUTH_GITHUB_CLIENT_SECRET=your-github-client-secret MODELENCE_AUTH_GITHUB_CLIENT_SCOPES=user:email,read:user ``` **Optional Configuration:** * `MODELENCE_AUTH_GITHUB_CLIENT_SCOPES`: Comma-separated list of OAuth scopes to request from GitHub. Defaults to `user:email` if not specified. Make sure to add `.env` to your `.gitignore` file to keep credentials secure. The GitHub authentication is automatically enabled when these configurations are set. No additional server code is needed. ## Client-Side Implementation To initiate GitHub Sign-In, redirect the user to the GitHub authentication endpoint: ```typescript theme={null} function handleGitHubSignIn() { // Redirect to GitHub OAuth flow window.location.href = '/api/_internal/auth/github'; } ``` ## UI Integration Add a GitHub Sign-In button to your UI: ```typescript theme={null} function LoginForm() { return (

Sign In

); } ``` ## How GitHub Sign-In Works 1. **Initiation** - User clicks "Sign in with GitHub" button 2. **Redirect** - User is redirected to GitHub's OAuth authorization page 3. **Authorization** - User grants permission to your app 4. **Callback** - GitHub redirects back to your app with an authorization code 5. **Token Exchange** - Your server exchanges the code for an access token and user information 6. **User Creation/Login** - If user doesn't exist, a new account is created; otherwise, user is logged in 7. **Session Creation** - A session is established and the user is authenticated ## Running inside an iframe The redirect flow above assumes your app can navigate in place. If your app is embedded in a **cross-origin iframe** — an embedded preview, a sandbox, a hosted playground — it cannot: providers refuse to render their consent screen inside an iframe, so the flow has to run in a top-level popup and the code has to be handed back to your page. Two things are needed, and both are off by default: 1. List the embedding origin in [`security.frameAncestors`](/api-reference/modelence/server/type-aliases/SecurityConfig#frameancestors) — Modelence denies cross-origin framing by default, so the frame is blocked before OAuth matters. 2. Follow [Embedded previews and popups](/react-native#embedded-previews-and-popups) for the popup flow itself. ## User Data Handling When a user signs in with GitHub, Modelence automatically: * Creates a user account if one doesn't exist * Links the GitHub account to the user profile * Retrieves profile information (first name, last name, username, email, avatar URL) * Marks the email as verified if GitHub has verified it * **Backfills missing profile fields** — If an existing user is missing `firstName`, `lastName`, or `avatarUrl`, these fields are automatically populated from their GitHub profile on login The user object will contain: ```typescript theme={null} { email: string; // GitHub account email handle: string; // Generated from GitHub username or email emailVerified: boolean; // true if GitHub email is verified githubId: string; // GitHub user ID firstName?: string; // First name from GitHub lastName?: string; // Last name avatarUrl?: string; // Avatar URL from GitHub } ``` ## Requesting Additional Scopes By default, Modelence requests basic profile information (`user:email` scope). If you need additional data from GitHub, you can configure additional scopes using the `MODELENCE_AUTH_GITHUB_CLIENT_SCOPES` environment variable or through Modelence Cloud. ### Configuring Scopes **Via Environment Variables:** ```bash theme={null} # Request multiple scopes (comma-separated) MODELENCE_AUTH_GITHUB_CLIENT_SCOPES=user:email,read:user,repo ``` **Via Modelence Cloud:** 1. Go to [cloud.modelence.com](https://cloud.modelence.com) 2. Navigate to **Authentication → Providers → GitHub** 3. Add the desired scopes in the scopes configuration field ### Common GitHub Scopes * `user:email` - Access to user's email addresses (default, required for authentication) * `read:user` - Read access to user profile data * `user` - Full access to user profile data (includes read and write) * `repo` - Access to public and private repositories * `public_repo` - Access to public repositories only * `gist` - Access to gists * `read:org` - Read-only access to organization membership For a complete list of available scopes, see the [GitHub OAuth scopes documentation](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps). **Note:** Only request the scopes your application actually needs. Users are more likely to authorize your app if it requests minimal permissions. ## Combining with Email/Password Authentication Users can have both GitHub and email/password authentication on the same account: ```typescript theme={null} import { loginWithPassword, logout } from 'modelence/client'; import { useState } from 'react'; function LoginOptions() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); return (

Sign In

{/* GitHub Sign-In */}
or
{/* Email/Password Sign-In */}
{ e.preventDefault(); await loginWithPassword({ email, password }); }}> setEmail(e.target.value)} placeholder="Email" /> setPassword(e.target.value)} placeholder="Password" />
); } ``` ## Troubleshooting **Authorization callback URL mismatch** * Ensure the callback URL in your GitHub OAuth App settings exactly matches your application URL * Check for trailing slashes and http vs https * Common format: `https://yourdomain.com/api/_internal/auth/github/callback` * You can only register one callback URL per OAuth App **Application suspended error** * Check your GitHub app settings to ensure it hasn't been suspended * Verify your account is in good standing **Invalid client credentials** * Verify your Client ID and Client Secret are correct * Check that environment variables are properly loaded * Ensure you copied the Client Secret correctly (it's only shown once) * Make sure credentials are from the correct GitHub OAuth App **No email address returned** * Some GitHub users have private email addresses * Users must have at least one public email or primary email set * You may need to handle cases where email is not provided * Consider prompting users to provide an email if not available from GitHub **Rate limiting errors** * GitHub enforces rate limits on OAuth endpoints * If developing locally, avoid making too many authentication requests in quick succession * Production apps typically don't hit these limits under normal usage # Google Sign-In Source: https://docs.modelence.com/authentication/google-sign-in Modelence supports OAuth authentication with Google, allowing users to sign in with their Google accounts. ## Prerequisites Before implementing Google Sign-In, you need to: 1. Create a project in the [Google Cloud Console](https://console.cloud.google.com/) 2. Configure the OAuth consent screen 3. Create OAuth 2.0 credentials (Client ID and Client Secret) 4. Configure authorized redirect URIs ## Google Cloud Console Setup 1. **Create a Project** * Go to [Google Cloud Console](https://console.cloud.google.com/) * Click "Select a project" → "New Project" * Name your project and click "Create" 2. **Configure OAuth Consent Screen** * Go to "APIs & Services" → "OAuth consent screen" * Choose user type (External for most applications) * Fill in the required fields: * App name * User support email * Developer contact information * Click "Save and Continue" * Add scopes if needed (profile and email are included by default) * Click "Save and Continue" 3. **Create OAuth Credentials** * Go to "APIs & Services" → "Credentials" * Click "Create Credentials" → "OAuth client ID" * Select "Web application" as the application type * Add a name for your OAuth client 4. **Configure Redirect URIs** * Under "Authorized JavaScript origins", add: * `http://localhost:3000` (for local development) * `https://yourdomain.com` (for production) * Under "Authorized redirect URIs", add: * `http://localhost:3000/api/_internal/auth/google/callback` (for local development) * `https://yourdomain.com/api/_internal/auth/google/callback` (for production) * Click "Create" > [!NOTE] > > This is the only redirect URI you need, including for native apps. React > Native sign-in reuses this same callback and returns to your app through a > deep link — see [React Native](/react-native#oauth-sign-in). 5. **Save Credentials** * Copy your **Client ID** and **Client Secret** * Store them securely (use environment variables or Modelence Cloud config) ## Server-Side Configuration Google Sign-In is built into Modelence and requires no additional packages. ### Option 1: Modelence Cloud (Recommended) The preferred way to configure Google authentication is through [Modelence Cloud](https://cloud.modelence.com/): 1. Go to [https://cloud.modelence.com/](https://cloud.modelence.com/) 2. Navigate to your project 3. Go to **Users → Auth Providers → Google** 4. Enable Google authentication 5. Enter your **Client ID** and **Client Secret** from Google Cloud Console 6. Save the configuration This approach allows you to manage your configuration centrally through an intuitive UI and keeps sensitive credentials secure. ### Option 2: Environment Variables Alternatively, you can use environment variables. Create a `.env` file in your project root: ```bash theme={null} MODELENCE_AUTH_GOOGLE_ENABLED=true MODELENCE_AUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com MODELENCE_AUTH_GOOGLE_CLIENT_SECRET=your-client-secret ``` Make sure to add `.env` to your `.gitignore` file to keep credentials secure. The Google authentication is automatically enabled when these configurations are set. No additional server code is needed. ## Client-Side Implementation To initiate Google Sign-In, redirect the user to the Google authentication endpoint: ```typescript theme={null} function handleGoogleSignIn() { // Redirect to Google OAuth flow window.location.href = '/api/_internal/auth/google'; } ``` ## UI Integration Add a Google Sign-In button to your UI: ```typescript theme={null} function LoginForm() { return (

Sign In

); } ``` ## How Google Sign-In Works 1. **Initiation** - User clicks "Sign in with Google" button 2. **Redirect** - User is redirected to Google's OAuth consent screen 3. **Authorization** - User grants permission to your app 4. **Callback** - Google redirects back to your app with an authorization code 5. **Token Exchange** - Your server exchanges the code for user information 6. **User Creation/Login** - If user doesn't exist, a new account is created; otherwise, user is logged in 7. **Session Creation** - A session is established and the user is authenticated ## Running inside an iframe The redirect flow above assumes your app can navigate in place. If your app is embedded in a **cross-origin iframe** — an embedded preview, a sandbox, a hosted playground — it cannot: providers refuse to render their consent screen inside an iframe, so the flow has to run in a top-level popup and the code has to be handed back to your page. Two things are needed, and both are off by default: 1. List the embedding origin in [`security.frameAncestors`](/api-reference/modelence/server/type-aliases/SecurityConfig#frameancestors) — Modelence denies cross-origin framing by default, so the frame is blocked before OAuth matters. 2. Follow [Embedded previews and popups](/react-native#embedded-previews-and-popups) for the popup flow itself. ## User Data Handling When a user signs in with Google, Modelence automatically: * Creates a user account if one doesn't exist * Links the Google account to the user profile * Retrieves profile information (first name, last name, email, avatar URL) * Marks the email as verified (since Google has verified it) * **Backfills missing profile fields** — If an existing user is missing `firstName`, `lastName`, or `avatarUrl`, these fields are automatically populated from their Google profile on login The user object will contain: ```typescript theme={null} { email: string; // Google account email handle: string; // Generated from email or name emailVerified: true; // Always true for Google sign-in googleId: string; // Google user ID firstName?: string; // First name from Google lastName?: string; // Last name from Google avatarUrl?: string; // Avatar URL from Google } ``` ## Combining with Email/Password Authentication Users can have both Google and email/password authentication on the same account: ```typescript theme={null} import { loginWithPassword, logout } from 'modelence/client'; import { useState } from 'react'; function LoginOptions() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); return (

Sign In

{/* Google Sign-In */}
or
{/* Email/Password Sign-In */}
{ e.preventDefault(); await loginWithPassword({ email, password }); }}> setEmail(e.target.value)} placeholder="Email" /> setPassword(e.target.value)} placeholder="Password" />
); } ``` ## Troubleshooting **Redirect URI Mismatch Error** * Ensure the redirect URI in Google Cloud Console exactly matches your application URL * Check for trailing slashes and http vs https * Common format: `https://yourdomain.com/api/_internal/auth/google/callback` **Invalid Client Error** * Verify your Client ID and Client Secret are correct * Check that environment variables are properly loaded * Ensure credentials are from the correct Google Cloud project **Access Blocked: Authorization Error** * Make sure Google+ API is enabled in your project * Verify your OAuth consent screen is configured * Check that your domain is authorized # Auth Hooks Source: https://docs.modelence.com/authentication/hooks The [AuthConfig](/api-reference/modelence/server/type-aliases/AuthConfig) type provides hooks for authentication events. Configure these in your `startApp` call under the **`auth:`** key. ## Validation Hooks ### `validateSignup` Called before a new user is created during email/password signup. Use this to enforce custom validation rules on signup data. Throw an error to reject the signup. ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ auth: { validateSignup: ({ email, firstName, lastName, password, handle, avatarUrl }) => { // Custom validation logic if (!firstName) { throw new Error('First name is required'); } }, }, }); ``` > [!WARNING] > > Don't enforce **password** rules here. `validateSignup` only runs at signup, so a user > could sign up with a compliant password and immediately reset to a weaker one — password > reset would only enforce the framework's built-in 8-character floor. Use > [`validatePassword`](#validatepassword) instead: it runs on every password-setting path. **Props:** | Property | Type | | - | - | | `email` | `string` | | `password` | `string` | | `firstName` | `string \| undefined` | | `lastName` | `string \| undefined` | | `avatarUrl` | `string \| undefined` | | `handle` | `string \| undefined` | **Returns:** `void | Promise` ### `validatePassword` Enforces your password policy on **every** path that sets a password — signup and password reset today, plus any future change-password flow. Throw an error to reject the password; the message is surfaced to the client. This is the hook to use for password rules. Modelence enforces a built-in floor of 8 characters (and a 128-character ceiling) before calling it, so your hook only needs to add your own rules on top. ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ auth: { validatePassword: ({ password, email, context }) => { if (password.length < 12) { throw new Error('Password must be at least 12 characters'); } if (password.toLowerCase().includes(email.split('@')[0])) { throw new Error('Password must not contain your email address'); } }, }, }); ``` The hook runs after the built-in length checks and before the password is hashed. On the reset path it runs *before* the reset token is consumed, so a user whose password is rejected can retry with the same link. **Props:** | Property | Type | | | - | - | - | | `password` | `string` | The candidate plaintext password | | `email` | `string` | Lowercased email of the account the password is set on | | `context` | `'signup' \| 'reset'` | Which flow is setting the password | **Returns:** `void | Promise` Use `context` when a flow needs different treatment — for example, checking a breach-database only on reset: ```typescript theme={null} validatePassword: async ({ password, context }) => { if (password.length < 12) { throw new Error('Password must be at least 12 characters'); } if (context === 'reset' && (await isBreachedPassword(password))) { throw new Error('This password has appeared in a data breach — pick another'); } }, ``` ### `onBeforeSignup` > [!NOTE] > > Available since `modelence@0.17.0`. Called after `validateSignup`, `validatePassword`, the built-in disposable-email check and the duplicate-email check, but before the user document is inserted. Use this to plug in a custom domain-policy check (e.g. a tenant-specific email-domain verification service) without disabling the built-in disposable-email check. Throw an error to reject the signup — the thrown error is re-thrown to the caller and `onSignupError` fires. Invoked for every provider, OAuth included, so it can gate who may sign up. Only signups reach this hook: an existing account signing in does not. On an OAuth signup, throw a `ModelenceError` such as `ValidationError` to show the user your message, delivered like any other OAuth error with the error's own `status` and the `signup_rejected` error code; any other error still blocks the signup but is reported as a generic failure, since its message may expose internals. `emailVerified` says whether ownership of the address is already proven: `true` for magic link, `false` for password signup (proven later through the verification link), and the provider's own value for OAuth. Check it before trusting an email for an allowlist decision. The built-in disposable-email check still skips OAuth signups, so check `provider` to keep a disposable-domain policy to email signups. > [!WARNING] > > Earlier versions ran this hook for `'email'` and `'magicLink'` signups only. Existing hooks now also run on OAuth signups (Google, GitHub, etc.), so a hook written with password signups in mind can start blocking OAuth signups. Check `provider` if a policy should apply to email signups only. ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ auth: { onBeforeSignup: async ({ email, emailVerified, firstName, lastName, handle, provider, connectionInfo }) => { const domain = email.split('@')[1]; const allowed = await isAllowedDomain(domain); if (!allowed) { throw new Error(`Signups from ${domain} are not allowed`); } }, }, }); ``` To replace the built-in disposable-email check entirely with your own logic, set `allowDisposableEmails: true` (also available since `modelence@0.17.0`) and enforce your policy in `onBeforeSignup`. ```typescript theme={null} startApp({ auth: { allowDisposableEmails: true, onBeforeSignup: async ({ email }) => { const verdict = await classifyEmailDomain(email); if (verdict === 'disposable') { throw new Error('Disposable email addresses are not allowed'); } }, }, }); ``` **Props:** | Property | Type | | - | - | | `email` | `string` | | `emailVerified` | `boolean` | | `firstName` | `string \| undefined` | | `lastName` | `string \| undefined` | | `handle` | `string \| undefined` | | `provider` | `AuthProvider` (`'email' \| 'magicLink' \| 'google' \| 'github' \| ...`) | | `connectionInfo` | `ConnectionInfo \| undefined` | **Returns:** `void | Promise` ### `validateProfileUpdate` Called before a user's profile is updated. Use this to enforce custom validation rules on profile updates. Throw an error to reject the update. ```typescript theme={null} startApp({ auth: { validateProfileUpdate: ({ firstName, lastName, avatarUrl, handle }) => { if (handle && handle.length < 3) { throw new Error('Handle must be at least 3 characters'); } }, }, }); ``` **Props:** | Property | Type | | - | - | | `firstName` | `string \| undefined` | | `lastName` | `string \| undefined` | | `avatarUrl` | `string \| undefined` | | `handle` | `string \| undefined` | **Returns:** `void | Promise` ## Custom Handle Generation ### `generateHandle` By default, handles are derived from the user's email address. This hook lets you generate custom handles based on the user's email and profile information. ```typescript theme={null} startApp({ auth: { generateHandle: ({ email, firstName, lastName }) => { // Generate a custom handle if (firstName && lastName) { return `${firstName.toLowerCase()}-${lastName.toLowerCase()}`; } return email.split('@')[0]; }, }, }); ``` **Props:** | Property | Type | | - | - | | `email` | `string` | | `firstName` | `string \| undefined` | | `lastName` | `string \| undefined` | **Returns:** `string | Promise` — The generated handle. If the handle conflicts with an existing one, Modelence will automatically append a numeric suffix. ## Auth Events ```typescript theme={null} startApp({ auth: { onAfterLogin: ({ user, provider, session, connectionInfo }) => { // Called after successful login console.log(`${user.handle} logged in via ${provider} from ${connectionInfo.ip}`); }, onLoginError: ({ error, provider, session, connectionInfo }) => { // Called when login fails console.error('Login error:', error.message); }, onAfterSignup: ({ user, provider, session, connectionInfo }) => { // Called after successful signup // Perfect place to send welcome emails or analytics }, onSignupError: ({ error, provider, session, connectionInfo }) => { // Called when signup fails console.error('Signup error:', error.message); }, onAfterEmailVerification: ({ user, session, connectionInfo }) => { // Called after successful email verification }, onEmailVerificationError: ({ error, session, connectionInfo }) => { // Called when email verification fails }, }, }); ``` ## Error Handling OAuth errors surface at the provider callback URL (`/api/_internal/auth/...`), which is a server route outside your client bundle. Nothing there can render your app's UI, so by default the user lands on a JSON body with no way back. Two options change that. ### `oauthErrorRedirectUrl` Use `oauthErrorRedirectUrl` to send the browser back into your app when a web OAuth flow fails. It accepts a path, resolved against your site URL (`MODELENCE_SITE_URL`), or an absolute URL. The failure is appended as `?error=&errorCode=`, the same contract a mobile flow delivers on its deep link, so your app can show it on a real page. ```typescript theme={null} startApp({ auth: { oauthErrorRedirectUrl: '/login', }, }); ``` Then read the params on that page: ```tsx theme={null} import { useSearchParams } from 'react-router'; function LoginPage() { const [searchParams] = useSearchParams(); const oauthError = searchParams.get('error'); // ...render oauthError inline in the form } ``` `error` is for display and its wording may change. Branch on `errorCode` (`invalid_state`, `email_exists`, `account_inactive`, `signup_rejected`, ...) for anything programmatic. When both `oauthErrorRedirectUrl` and `errorComponent` are set, the redirect wins and `errorComponent` is not called. ### `errorComponent` (deprecated) `errorComponent` is deprecated in favor of `oauthErrorRedirectUrl`. It renders OAuth errors as a standalone HTML document at the callback URL instead of JSON, which means the page cannot use your app's UI. It is still honored for existing apps, but is ignored whenever `oauthErrorRedirectUrl` is set. ```typescript theme={null} startApp({ auth: { errorComponent: ({ error, statusCode }) => { // Safely escape the error string to prevent XSS vulnerabilities const escapeHtml = (str: string | number) => String(str).replace(/[&<>"']/g, m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[m as any] || m); return `

Error ${escapeHtml(statusCode)}

${escapeHtml(error)}

`; }, }, }); ``` ## Full Example ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ auth: { validateSignup: ({ email, password, firstName }) => { if (!firstName) { throw new Error('First name is required'); } }, validatePassword: ({ password }) => { if (password.length < 12) { throw new Error('Password must be at least 12 characters'); } }, validateProfileUpdate: ({ handle }) => { if (handle && !/^[a-z0-9-]+$/.test(handle)) { throw new Error('Handle can only contain lowercase letters, numbers, and hyphens'); } }, onBeforeSignup: async ({ email }) => { const domain = email.split('@')[1]; if (domain === 'blocked.example') { throw new Error(`Signups from ${domain} are not allowed`); } }, generateHandle: ({ email, firstName, lastName }) => { if (firstName && lastName) { return `${firstName}-${lastName}`.toLowerCase(); } return email.split('@')[0]; }, oauthErrorRedirectUrl: '/login', onAfterSignup: ({ user }) => { console.log('Welcome!', user.handle); }, onAfterLogin: ({ user, provider }) => { console.log(`${user.handle} logged in via ${provider}`); }, }, }); ``` # Auth Overview Source: https://docs.modelence.com/authentication/index Modelence provides a comprehensive built-in authentication system with support for email/password authentication, email verification, password reset, and session management. This guide explains how authentication works in Modelence and how to implement it in your application. ## Overview Modelence authentication includes: * **Email/Password Authentication** - User signup and login with email and password * **Session Management** - Secure session handling with automatic token rotation * **[User Management](/authentication/user-management)** - User profile and role management * **[Email Verification](/authentication/email-verification)** - Optional email verification for new signups * **[Password Reset](/authentication/password-reset)** - Secure password reset flow with email tokens * **[Hooks](/authentication/hooks)** - Add custom handlers and error rendering components for your authentication flow * **[Rate Limiting](/authentication/rate-limiting)** - Built-in protection against brute force attacks * **[Google Sign-In](/authentication/google-sign-in)** - OAuth authentication with Google accounts * **[GitHub Sign-In](/authentication/github-sign-in)** - OAuth authentication with GitHub accounts ## Where to configure what Modelence splits authentication configuration across two top-level keys in `startApp`: * **`auth: { ... }`** — authentication *lifecycle*: validation hooks (`validateSignup`, `validatePassword`, `validateProfileUpdate`), event callbacks (`onAfterLogin`, `onAfterSignup`, `onAfterEmailVerification`, …), `generateHandle`, OAuth linking behavior, and `rateLimits`. See [AuthConfig](/api-reference/modelence/server/type-aliases/AuthConfig) and [Hooks](/authentication/hooks). * **`email: { ... }`** — email *delivery*: the email provider, sender address, and per-flow templates/subjects/redirect URLs for `verification` and `passwordReset`. See [Email Configuration](/email). The two are complementary: `email:` controls whether and how the verification/reset email is delivered; `auth:` controls what happens when the user clicks the link (and the rest of the auth lifecycle). ## How Authentication Works ### Session Management When a user visits your application, Modelence automatically creates a session: 1. **Session Creation** - A secure session token is generated using cryptographically random bytes 2. **Token Storage** - The session token is stored in the database and sent to the client 3. **Automatic Expiration** - Sessions expire after 7 days of inactivity 4. **Heartbeat Updates** - Active sessions are automatically renewed through periodic heartbeat requests Sessions are stored in the `_modelenceSessions` collection and tracked with the following properties: ```typescript theme={null} { authToken: string; // Secure random token createdAt: Date; // Session creation timestamp expiresAt: Date; // Automatic expiration date userId: ObjectId | null; // Associated user (null for guest sessions) } ``` ### User Authentication Flow #### Signup Process When a user signs up with email and password: 1. **Validation** - Email format, password strength, and profile fields are validated 2. **Validate Signup** (Optional) - If provided, validates signup using `validateSignup` hook 3. **Validate Password** (Optional) - If provided, the `validatePassword` hook enforces your password policy. This hook also runs on password reset, so a policy set here can't be bypassed by resetting to a weaker password. 4. **Handle Check** - A requested handle that is already taken is rejected 5. **Duplicate Check** - System checks if email already exists. This runs after every validation step, so a request that fails validation gets the same error whether or not the email is registered 6. **Password Hashing** - Password is securely hashed using bcrypt (never stored in plain text) 7. **User Creation** - User record is created in the `_modelenceUsers` collection 8. **Session Linking** - The session is linked to the new user 9. **Email Verification** (Optional) - If enabled, a verification email is sent #### Login Process When a user logs in: 1. **Credential Verification** - Email and password are validated against stored credentials 2. **Session Update** - Current session is linked to the authenticated user 3. **User Data** - User information is returned to the client 4. **State Update** - Client-side session state is updated ### OAuth Account Linking When a user signs in with an OAuth provider (Google or GitHub) using an email that already matches an existing email/password account, behavior is controlled by the [`oauthAccountLinking`](/api-reference/modelence/server/type-aliases/AuthConfig#oauthaccountlinking) auth config option: * **`'manual'`** (default) - The OAuth sign-in is rejected with an error: *"User with this email already exists. Please log in instead."* The user must log in with their existing password first and link the provider deliberately. * **`'auto'`** - The OAuth provider is automatically linked to the existing account, but only when **both** the OAuth-provided email is verified by the provider **and** the matching email on the existing account is also marked verified locally. This dual-verification requirement prevents pre-registration account takeover (e.g., someone registering a password account against an email they don't own, then waiting for the real owner to sign in via OAuth). When auto-linking succeeds, missing `firstName`, `lastName`, and `avatarUrl` fields are backfilled from the provider profile. If either email is unverified — even in `'auto'` mode — the sign-in is rejected with the same error. Once an OAuth provider is linked, subsequent sign-ins with the same provider look up the user directly by the provider's user ID, regardless of email. ## Basic Implementation ### Client-Side Usage #### Signup ```typescript theme={null} import { signupWithPassword } from 'modelence/client'; async function handleSignup(email: string, password: string) { try { await signupWithPassword({ email, password }); // User is now signed up // If email verification is disabled, user is automatically logged in } catch (error) { console.error('Signup failed:', error.message); } } // You can also pass optional profile fields during signup await signupWithPassword({ email: 'test@example.com', password: 'securepassword', firstName: 'John', lastName: 'Doe', avatarUrl: 'https://example.com/avatar.jpg', handle: 'johndoe', }); ``` #### Login ```typescript theme={null} import { loginWithPassword } from 'modelence/client'; async function handleLogin(email: string, password: string) { try { const user = await loginWithPassword({ email, password }); console.log('Logged in as:', user.handle); } catch (error) { console.error('Login failed:', error.message); } } ``` #### Logout ```typescript theme={null} import { logout } from 'modelence/client'; async function handleLogout() { await logout(); // User is now logged out } ``` #### Update Profile ```typescript theme={null} import { updateProfile } from 'modelence/client'; async function handleUpdateProfile() { try { const user = await updateProfile({ firstName: 'John', lastName: 'Doe', avatarUrl: 'https://example.com/avatar.jpg', handle: 'johndoe', }); console.log('Profile updated:', user.handle); } catch (error) { console.error('Update failed:', error.message); } } ``` All fields are optional — pass only the ones you want to update. Modelence automatically updates the user in `useSession()`. #### Accessing Current User ```typescript theme={null} import { useSession } from 'modelence/client'; function MyComponent() { const { user } = useSession(); if (!user) { return
Please log in
; } return
Welcome, {user.handle}!
; } ``` ## API Reference ### Client Functions * [signupWithPassword](/api-reference/modelence/client/functions/signupWithPassword) - Sign up with email and password * [loginWithPassword](/api-reference/modelence/client/functions/loginWithPassword) - Log in with email and password * [logout](/api-reference/modelence/client/functions/logout) - Log out current user * [useSession](/api-reference/modelence/client/functions/useSession) - Access current user session * [verifyEmail](/api-reference/modelence/client/functions/verifyEmail) - Verify email with token * [sendResetPasswordToken](/api-reference/modelence/client/functions/sendResetPasswordToken) - Request password reset * [resetPassword](/api-reference/modelence/client/functions/resetPassword) - Set a new password (token is exchanged server-side via cookie) ### Server Types * [AuthConfig](/api-reference/modelence/server/type-aliases/AuthConfig) - Authentication configuration * [UserInfo](/api-reference/modelence/server/type-aliases/UserInfo) - User information type * [dbUsers](/api-reference/modelence/server/variables/dbUsers) - User database collection ### Error Types * [AuthError](/api-reference/modelence/index/classes/AuthError) - Authentication errors * [ValidationError](/api-reference/modelence/index/classes/ValidationError) - Validation errors * [RateLimitError](/api-reference/modelence/index/classes/RateLimitError) - Rate limit errors # Magic Link Source: https://docs.modelence.com/authentication/magic-link Modelence supports passwordless authentication with magic links: the user enters their email address and receives an email with a single-use sign-in **link** and a matching **one-time code**. Clicking the link signs them in; typing the code does the same — useful on mobile apps or when the email is read on a different device. > [!NOTE] > > Magic link sign-in and sign-up are available since `modelence@0.22.0`. Magic link can also work as a combined sign-in and sign-up: with the `allowSignup` option enabled, an account is created automatically when the link or code is used for an email that is not registered yet — just like OAuth sign-in. This is disabled by default (see [Sign-Up Behavior](#sign-up-behavior)). > The magic link email delivery setup below (provider, sender, template, redirect URL) is configured under the **`email:`** key of `startApp`. To run code on related auth events, register callbacks under **`auth:`** — see [Auth Hooks](/authentication/hooks). ## Configuration Magic link authentication is disabled by default. Enable it under the `auth:` key of `startApp` and configure the email delivery under the `email:` key: ```typescript theme={null} import { startApp } from 'modelence/server'; import resendProvider from '@modelence/resend'; startApp({ auth: { magicLink: { enabled: true, // Optional: also create accounts for unknown emails (default: false) allowSignup: true, }, }, email: { provider: resendProvider, from: 'noreply@yourdomain.com', magicLink: { subject: 'Your sign-in link', redirectUrl: 'https://yourdomain.com/auth/magic-link', }, }, }); ``` `redirectUrl` is the page in your app that completes the sign-in. Modelence redirects here **after** validating the token and storing it in an `httpOnly` cookie, so this URL never carries the token. This is also where you call [`loginWithMagicLink()`](#complete-the-sign-in). ## How It Works 1. User requests a magic link by providing their email 2. A secure single-use link token and a 6-digit one-time code are generated, hashed, and stored in the database (only the hashes are stored, never the raw values). Both expire after 15 minutes, and using either one invalidates both 3. An email with the sign-in link and the code is sent to the address. The response is always the same generic message, so it never reveals whether an email is registered (with `allowSignup` disabled, unknown emails get the same response but no email is sent) 4. The link points at a Modelence server route, **not** your SPA page. That route validates the token, stores it in a short-lived `httpOnly` cookie, and redirects to your configured `redirectUrl` **without the token in the URL**. The token is **not** consumed at this step, so email security scanners that prefetch links cannot burn it 5. On that page, you call `loginWithMagicLink()` — the token is read server-side from the cookie, atomically consumed (single-use), and the user is signed in. Alternatively, the user types the code anywhere and you call `loginWithOneTimeCode({ email, code })` 6. If no account exists for the email and `allowSignup` is enabled, one is created first (see [Sign-Up Behavior](#sign-up-behavior)) 7. The email address is marked as verified — using the emailed link or code proves ownership > [!NOTE] > > The magic link token never reaches your client code or appears in a browser URL — it is exchanged server-side through an `httpOnly` cookie, the same pattern used by [password reset](/authentication/password-reset). This closes the window where a token could leak via the address bar, browser history, or the `Referer` header. ### Base URL requirement The magic link is built from your site's base URL, so you must set it via the `_system.site.url` config (or the `MODELENCE_SITE_URL` environment variable). If it isn't set, sending a magic link fails with a clear error rather than emailing a broken link. ### Sender address requirement `email.from` must be set to an address on your own domain. There is no default sender — if it isn't configured, sending a magic link fails with a clear error rather than sending from an address your email provider can't authenticate (SPF/DKIM). ## Client Implementation ### Request a Magic Link ```typescript theme={null} import { sendMagicLink } from 'modelence/client'; async function handleMagicLinkRequest(email: string) { try { await sendMagicLink({ email }); console.log('Check your email for a sign-in link'); } catch (error) { console.error('Error:', error.message); } } ``` A typical email form: ```tsx theme={null} import { useState } from 'react'; import { sendMagicLink } from 'modelence/client'; function MagicLinkForm() { const [isSent, setIsSent] = useState(false); if (isSent) { return

Check your email — we've sent you a sign-in link.

; } return (
{ event.preventDefault(); const email = new FormData(event.currentTarget).get('email') as string; await sendMagicLink({ email }); setIsSent(true); }} >
); } ``` ### Complete the Sign-In The user lands on your `redirectUrl` page after clicking the email link. The token is already held in an `httpOnly` cookie, so no arguments are needed: ```tsx theme={null} import { useEffect, useRef, useState } from 'react'; import { loginWithMagicLink } from 'modelence/client'; function MagicLinkLoginPage() { const [error, setError] = useState(null); const startedRef = useRef(false); useEffect(() => { // Guard against double-invocation (React StrictMode) — the token is // single-use, so the mutation must only run once. if (startedRef.current) return; startedRef.current = true; // The landing route redirects here with ?status=error when the link is // invalid or expired. const params = new URLSearchParams(window.location.search); if (params.get('status') === 'error') { setError(params.get('message') ?? 'This sign-in link is invalid or has expired.'); return; } loginWithMagicLink() .then(() => { window.location.href = '/'; }) .catch((err) => setError(err.message)); }, []); if (error) { return

{error}

; } return

Signing you in…

; } ``` ### Sign In with the One-Time Code The same email carries a 6-digit code, so users can complete the sign-in without clicking the link — the natural path for native apps (Expo / React Native) where deep links aren't set up, or when the email is opened on a different device than the one signing in: ```tsx theme={null} import { useState } from 'react'; import { loginWithOneTimeCode } from 'modelence/client'; function OneTimeCodeForm({ email }: { email: string }) { const [error, setError] = useState(null); return (
{ event.preventDefault(); const code = new FormData(event.currentTarget).get('code') as string; try { await loginWithOneTimeCode({ email, code }); // Signed in — navigate to your app's home screen } catch (err) { setError((err as Error).message); } }} > {error &&

{error}

}
); } ``` Whitespace and dashes in the typed code are ignored, so `482 193` and `482-193` both work. Each code tolerates only a few wrong guesses before it is invalidated, and using the code invalidates the link (and vice versa). ## Sign-Up Behavior Automatic account creation is a separate opt-in from enabling magic links, and it is **disabled by default**: unknown emails receive no email (the response stays the same generic message), and a link or code can never create an account. Enable it with `allowSignup`: ```typescript theme={null} startApp({ auth: { magicLink: { enabled: true, allowSignup: true, }, }, }); ``` With `allowSignup` enabled, when a magic link is used for an email with no existing account, Modelence creates one automatically: * The account is created with the email already marked as **verified** * The handle is derived from the email local-part (or via your [`generateHandle`](/authentication/hooks) hook) * The [`onBeforeSignup`](/authentication/hooks) hook runs first and can reject the signup by throwing; [`onAfterSignup`](/authentication/hooks) fires after the account is created * No password is set — the user can keep signing in with magic links, add a password later via password reset, or link an OAuth provider For existing accounts, magic link works regardless of how the account was originally created (password or OAuth) — [`onAfterLogin`](/authentication/hooks) fires as usual. All magic link hook invocations use `provider: 'magicLink'`. ## Custom Email Template The template receives both credentials — `magicLinkUrl` (the clickable link) and `code` (the typed one-time code) — so you can render either or both: ```typescript theme={null} startApp({ email: { provider: resendProvider, from: 'noreply@yourdomain.com', magicLink: { subject: 'Sign in to YourApp', template: ({ name, email, magicLinkUrl, code }) => `

Sign in to YourApp

Hi ${name || 'there'},

Click the button below to sign in as ${email}:

Sign In

Or enter this code in the app:

${code}

The link and code can only be used once and will expire in 15 minutes.

If you didn't request this, you can safely ignore this email.

`, redirectUrl: 'https://yourdomain.com/auth/magic-link', }, }, }); ``` ## Security * **Single-use, short-lived credentials** — the link and code work exactly once (using either invalidates both) and expire after 15 minutes * **Hashed at rest** — only SHA-256 hashes are stored, so a database leak does not expose usable links * **Scanner-safe** — the emailed link only stashes the token in a cookie; it is consumed by the follow-up client call, so corporate email scanners that prefetch links do not invalidate them * **Guess-resistant codes** — each code allows only a handful of wrong guesses before it is invalidated, and code attempts are separately rate limited per IP and per email * **No enumeration** — requesting a link always returns the same generic response, whether or not the email is registered; a wrong code returns the same error as an unknown email * **Rate limited** — magic link requests and code attempts are limited per IP and per email address; see [Rate Limiting](/authentication/rate-limiting) to customize the `magicLink` and `oneTimeCode` buckets # Password Reset Source: https://docs.modelence.com/authentication/password-reset Modelence provides a secure password reset flow with email tokens. > The reset email delivery setup below (provider, sender, template, redirect URL) is configured under the **`email:`** key of `startApp`. To run code on related auth events, register callbacks under **`auth:`** — see [Auth Hooks](/authentication/hooks). ## Configuration Configure password reset emails in your server setup: ```typescript theme={null} import { startApp } from 'modelence/server'; import resendProvider from '@modelence/resend'; startApp({ email: { provider: resendProvider, from: 'noreply@yourdomain.com', passwordReset: { subject: 'Reset your password', redirectUrl: 'https://yourdomain.com/reset-password', }, }, }); ``` `redirectUrl` is the page in your app where the user enters their new password. Modelence redirects here **after** validating the token and storing it in an `httpOnly` cookie, so this URL never carries the token. This is also where you call [`resetPassword({ password })`](#reset-password). ## How It Works 1. User requests a password reset by providing their email 2. A secure reset token is generated, hashed, and stored in the database (only the hash is stored, never the raw token) 3. An email with a reset link is sent to the user 4. The link points at a Modelence server route, **not** your SPA page. That route validates the token, stores it in a short-lived `httpOnly` cookie, and redirects to your configured `redirectUrl` **without the token in the URL** 5. On that page, the user enters their new password and you call `resetPassword({ password })` — the token is read server-side from the cookie, so it never reaches client JavaScript 6. The new password is checked against the built-in length limits and your [`validatePassword`](/authentication/hooks#validatepassword) hook, if configured 7. Password is updated and the token is invalidated (single-use) 8. If the user's email was not yet verified, it is automatically marked as verified Since the user must receive the reset email to complete the flow, a successful password reset proves ownership of the email address. > [!NOTE] > > This is a **set-or-reset** flow. It works for accounts that have no password yet — for example those created via [magic link](/authentication/magic-link) or OAuth — letting the user add a local password. Completing it sets the password whether or not one existed before. > [!NOTE] > > Modelence enforces a built-in minimum of 8 characters here. To apply a stricter policy, configure the [`validatePassword`](/authentication/hooks#validatepassword) hook — it runs on **both** signup and reset, so users can't sidestep your rules by resetting to a weaker password. A policy enforced only in `validateSignup` is bypassable this way. > > If your hook rejects the password, the reset token is **not** consumed, so the user can retry with the same link. > [!NOTE] > > The reset token never reaches your client code or appears in a browser URL — it is exchanged server-side through an `httpOnly` cookie. This closes the window where a token could leak via the address bar, browser history, or the `Referer` header. > [!NOTE] > > The token cookie is sent with credentialed requests, so it works even when your SPA and Modelence API are on different origins. For that cross-origin case, the API must respond with `Access-Control-Allow-Credentials: true` and a specific (non-wildcard) allowed origin, otherwise the browser drops the cookie and the reset fails. ### Base URL requirement The reset email link is built from your site's base URL, so you must set it via the `_system.site.url` config (or the `MODELENCE_SITE_URL` environment variable). If it isn't set, sending a reset token fails with a clear error rather than emailing a broken link. ## Client Implementation ### Request Password Reset ```typescript theme={null} import { sendResetPasswordToken } from 'modelence/client'; async function handleForgotPassword(email: string) { try { await sendResetPasswordToken({ email }); console.log('Password reset email sent'); } catch (error) { console.error('Error:', error.message); } } ``` ### Reset Password The user lands on your `redirectUrl` page after clicking the email link. The token is already held in an `httpOnly` cookie, so you only collect the new password — don't pass a token: ```typescript theme={null} import { resetPassword } from 'modelence/client'; async function handleResetPassword(newPassword: string) { try { await resetPassword({ password: newPassword }); console.log('Password reset successful'); } catch (error) { console.error('Reset failed:', error.message); } } ``` > [!WARNING] > > Passing a `token` to `resetPassword({ token, password })` is **deprecated**. It exists only for legacy flows that still carry the token client-side and will be removed. New apps should rely on the server-side cookie exchange and submit just the password. ## Custom Reset Email Template ```typescript theme={null} startApp({ email: { provider: resendProvider, from: 'noreply@yourdomain.com', passwordReset: { subject: 'Reset Your Password', template: ({ name, email, resetUrl }) => `

Password Reset Request

Hi ${name || 'there'},

We received a request to reset your password. Click the button below to proceed:

Reset Password

If you didn't request this, you can safely ignore this email.

This link will expire in 1 hour.

`, redirectUrl: 'https://yourdomain.com/reset-password', }, }, }); ``` # Auth Rate Limiting Source: https://docs.modelence.com/authentication/rate-limiting Modelence includes built-in rate limiting on all authentication endpoints to protect against brute force attacks and abuse. ## Default Rate Limits * **Signup**: 20 attempts per 15 minutes, 200 per day (per IP) * **Login**: 50 attempts per 15 minutes, 500 per day (per IP); 10 failed attempts per 15 minutes (per email) * **Email Verification** (resend): 10 per 15 minutes, 100 per day (per IP); 1 per 60 seconds, 10 per day (per user) * **Password Reset**: 10 per 15 minutes, 100 per day (per IP); 5 per hour, 10 per day (per email) * **Magic Link**: 10 per 15 minutes, 100 per day (per IP); 5 per hour, 10 per day (per email) * **One-Time Code**: 20 per 15 minutes, 100 per day (per IP); 10 per hour, 20 per day (per email) These limits are automatically enforced and will throw a [RateLimitError](/api-reference/modelence/index/classes/RateLimitError) when exceeded. Once the per-email sign-in limit is full, **every attempt is rejected with 429, including attempts with the correct password**. This is deliberate: if a correct password still worked when the bucket was full, the limit would not stop guessing. The trade-off is a targeted lockout — about 10 requests every 15 minutes from any IP can keep a known account locked out while the attacker keeps going. Password reset and magic link still work. To use a different balance, change or remove the rule with [`authConfig.rateLimits.signin`](/api-reference/modelence/server/type-aliases/AuthRateLimitsConfig). ## Handling Rate Limit Errors ```typescript theme={null} import { loginWithPassword } from 'modelence/client'; import { RateLimitError } from 'modelence'; async function handleLogin(email: string, password: string) { try { await loginWithPassword({ email, password }); } catch (error) { if (error instanceof RateLimitError) { console.error('Too many attempts. Please try again later.'); } else { console.error('Login failed:', error.message); } } } ``` ## Disposable Email Detection Aside from rate limiting, Modelence also includes automatic protection against 100k+ disposable email services, and keeps a periodically updated dataset of all disposable email providers. *** For defining custom rate limits on your own modules, see [Custom Rate Limiting](/rate-limiting). # User Management Source: https://docs.modelence.com/authentication/user-management Modelence stores user data in the `dbUsers` collection, which you can query and update directly from your server-side code. ## Finding Users ```typescript theme={null} import { dbUsers, ObjectId } from 'modelence/server'; // Find user by ID const user = await dbUsers.findById(userId); // Find user by email const user = await dbUsers.findOne({ 'emails.address': 'john@example.com' }); // Find all users with a specific role const admins = await dbUsers.fetch({ roles: 'admin' }); ``` ## Accessing the current user in method calls Use the `user` object from the context in your query/mutation handler to access the currently authenticated user: ```typescript theme={null} import { Module } from 'modelence/server'; export default new Module('profile', { queries: { getMyProfile: async (args, { user }) => { if (!user) { return null; } return { id: user.id, handle: user.handle, roles: user.roles, }; } } }); ``` ## Disabling & Deleting Users Modelence provides helper functions for safely disabling or deleting users: ```typescript theme={null} import { disableUser, deleteUser, ObjectId } from 'modelence/server'; // Set user's status to `disabled` and clears all sessions (preserves data, prevents login) await disableUser(new ObjectId(userId)); // Delete a user (anonymizes data, clears all login methods) await deleteUser(new ObjectId(userId)); ``` # Availability Source: https://docs.modelence.com/cloud/availability Failovers and deploys Modelence Cloud operates production services to a 99.9% uptime target. Real-time and historical availability, and any ongoing incidents, are published at [status.modelence.com](https://status.modelence.com). ## Containers An environment's service runs as one or more containers on AWS Fargate, spread across two availability zones in the environment's [region](/cloud/regions). Each container is checked every 30 seconds to confirm the app still accepts connections on its `PORT`, and a container that fails three checks in a row is replaced. Deploys and container replacements never take the app down: a new container is always started and checked before the one it replaces is stopped. To also keep serving through an app crash or the loss of a whole availability zone, run two or more containers, so the others handle traffic while one is replaced. Each container is billed separately. ## Deploys A deploy starts the new version's containers next to the running ones, and the old containers are stopped only once the new ones are up and passing checks. If the new version keeps crashing, the deploy is rolled back automatically and the previous version keeps serving, so a broken build never replaces a working one. ## Databases Managed databases store their data redundantly, so losing a single machine doesn't lose data. When the machine serving a database fails, the database is brought back on a healthy one automatically, which takes from a few seconds to a few minutes depending on the database, and most database clients reconnect on their own once it's back. Production databases are also [backed up](/cloud/backups) at least every six hours. # Backups Source: https://docs.modelence.com/cloud/backups Database backups and restore Production databases on Modelence Cloud are backed up automatically on every plan. There is nothing to turn on or configure. ## What's backed up * **Schedule:** a snapshot of the database is taken at least every six hours. * **Retention:** snapshots are kept on a rolling schedule. Recent snapshots are kept close together and older ones are thinned out over time, and the oldest are gone within 12 months. * **Encryption:** snapshots are encrypted at rest, like the database itself. Restores come from these snapshots, so a database can be brought back to the time of any kept snapshot, not to an arbitrary moment between two of them. > [!WARNING] > > Deleting a database resource permanently deletes its data and its backups. ## Restoring from a backup Restores are done by the Modelence support team. Email [support@modelence.com](mailto:support@modelence.com) with: * the app and environment (the app ID is enough), * the database, if the environment has more than one, * roughly what point in time you want to go back to. We find the closest snapshot, tell you its time, and confirm with you before anything changes in the environment. You can also ask this way for the time of the most recent snapshot. ## Exporting data Each database's connection string reaches the app at runtime as an environment variable. To export a database, connect with that string and use the database's standard dump tool, and load a dump back with its matching restore tool. > [!NOTE] > > The connection string contains the database password. Keep it out of your repository and anywhere > else it could be read. # Databases Source: https://docs.modelence.com/cloud/databases Managed MongoDB, PostgreSQL and Redis databases Modelence Cloud runs managed MongoDB, PostgreSQL and Redis databases next to the app. Each one is created in the environment's [region](/cloud/regions), its connection string reaches the app as an [environment variable](/cloud/environment-variables), and it is [backed up](/cloud/backups) in production. A database is a resource in [`modelence.config.json`](/deploy/setup#modelence-config-json-reference), and `env` passes its connection string to the app: ```json modelence.config.json theme={null} { "resources": { "api": { "type": "service", "build": { "commands": ["npm ci"] }, "start": { "commands": ["node server.js"] } }, "main-db": { "type": "postgres", "plan": "postgres-1gb" }, "cache": { "type": "redis" } }, "env": { "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" }, "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" } } } ``` A `url` output is the full connection string, over TLS. The other outputs are its parts, for clients that read them separately. The [reference](/deploy/setup#modelence-config-json-reference) lists every plan and output. ## Lifecycle A deploy creates every managed resource the file declares that the environment doesn't have yet, and the new version starts only once they are ready. Resources are matched by name, so the same file works in every environment: * A resource that already exists is kept as it is, with its data. `plan` is read only when the resource is created, so changing it later has no effect. * A resource removed from the file is not deleted, and it is billed until it is. * Renaming a resource creates a new, empty one, and the old one stays until it is deleted. Deleting a managed resource permanently deletes its data and its backups. ## Databases hosted elsewhere An app can also use a database hosted somewhere else, such as Supabase, Neon or PlanetScale. Keep its connection code and declare its URL and keys in `env` as secrets. # Environment Variables Source: https://docs.modelence.com/cloud/environment-variables Variables Modelence Cloud provides to every app, and how to declare your own An app on Modelence Cloud reads its settings and secrets from environment variables. Some are provided by the platform in every environment, and the rest are declared in the `env` section of [`modelence.config.json`](/deploy/setup#modelence-config-json-reference) and set per environment. ## Provided variables | Variable | Value | | - | - | | `PORT` | The port the web process must listen on. | | `SITE_URL`, `ROOT_URL` | The environment's public URL. Both hold the same value. | | `MONGODB_URI`, `MONGO_URL` | The connection string of the environment's MongoDB database. Both hold the same value. | Names starting with `MODELENCE_`, and `PORT`, are reserved and cannot be declared by the app. ## Declaring variables Each variable the app expects is declared by name in `env`: ```json modelence.config.json theme={null} { "env": { "API_BASE_PATH": { "value": "/api" }, "STRIPE_SECRET_KEY": { "type": "secret" }, "SLACK_WEBHOOK_URL": { "type": "secret", "required": false }, "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" } } } ``` * **`text`** (the default) is a plain setting. A `value` in the file is the committed default, and a value set for an environment overrides it. * **`secret`** is for keys, tokens and passwords. It never carries a `value` in the file, and its value is encrypted and left out of the variable list in the dashboard. Environment members can open a secret to view or change it, and every view is logged. * **`resource`** takes its value from a managed database or cache declared in the same file. It can't be set by hand. See [Databases](/cloud/databases). A deploy asks for every required variable that has no value in the target environment, and a CI deploy fails without one. Mark a variable the app can run without `"required": false`. ## Build and runtime A variable reaches the running app by default. Anything the build needs as well, such as a `VITE_*` or `NEXT_PUBLIC_*` value a bundler inlines into the frontend, also needs `"scopes": ["build", "runtime"]`. A value scoped to `["build"]` alone, such as a private registry token, never reaches the running app. A bundler puts inlined values into code that every visitor downloads, so a secret must never be inlined. Resource variables reach the running app only. ## When changes take effect Containers read their variables when they start, so a changed value reaches the running app on the next restart or deploy. A build variable takes effect on the next deploy. In a [local environment](/setup), the environment's values reach the app when it starts on your machine, so they never need to be copied into the project. # Regions Source: https://docs.modelence.com/cloud/regions Supported deployment regions Modelence Cloud runs on AWS. Each production environment runs in one region, which you pick when you deploy the environment for the first time. The app's containers and its MongoDB, PostgreSQL and Redis databases are all created in that region. ## Available regions | Region | AWS region | Status | | - | - | - | | US West (Oregon) | `us-west-2` | Available | | Canada (Central) | `ca-central-1` | Available | | Europe (Frankfurt) | `eu-central-1` | Available | | US East (N. Virginia) | `us-east-1` | On request | | US East (Ohio) | `us-east-2` | On request | | US West (N. California) | `us-west-1` | On request | | South America (São Paulo) | `sa-east-1` | On request | | Europe (Ireland) | `eu-west-1` | On request | | Europe (London) | `eu-west-2` | On request | | Europe (Paris) | `eu-west-3` | On request | | Europe (Stockholm) | `eu-north-1` | On request | | Asia Pacific (Mumbai) | `ap-south-1` | On request | | Asia Pacific (Tokyo) | `ap-northeast-1` | On request | | Asia Pacific (Seoul) | `ap-northeast-2` | On request | | Asia Pacific (Osaka) | `ap-northeast-3` | On request | | Asia Pacific (Singapore) | `ap-southeast-1` | On request | | Asia Pacific (Sydney) | `ap-southeast-2` | On request | Regions marked **Available** can be picked by any organization. To deploy to a region marked **On request**, email [support@modelence.com](mailto:support@modelence.com) with the region you need, and we'll enable it for your organization. Sandbox environments always run in US West (Oregon). # Configuration Source: https://docs.modelence.com/configuration Define typed configuration schemas and access them with Module.getConfig and createClientModule(...).getConfig. Available since modelence@0.15.0. Modelence modules support a `configSchema` that lets you define typed, named configuration values. These values can be managed through Modelence Cloud and accessed at runtime via typed accessors. This is the recommended way to store settings like API keys, feature toggles, default values, and any other configuration your module needs — without hardcoding them or relying solely on environment variables. ## Version Requirements Configuration accessors in this guide require: * `Module.getConfig()` - available since `modelence@0.15.0` * `createClientModule(...).getConfig()` - available since `modelence@0.15.0` ## Defining a Config Schema Add a `configSchema` to your module definition. Each key becomes a configuration value namespaced under the module name: ```typescript title="src/server/payments/index.ts" theme={null} import { Module } from 'modelence/server'; export default new Module('payments', { configSchema: { apiKey: { type: 'secret', default: '', isPublic: false, }, currency: { type: 'string', default: 'USD', isPublic: true, }, maxRetries: { type: 'number', default: 3, isPublic: false, }, }, }); ``` Each config field requires three properties: | Property | Type | Description | | - | - | - | | `type` | `ConfigType` | The data type — see [Config Types](#config-types) below | | `default` | *(matches type)* | Default value used when no value has been set | | `isPublic` | `boolean` | Whether this value is accessible on the client | ## Config Types The `type` field accepts one of five values: | Type | Value Type | Description | | - | - | - | | `'string'` | `string` | A short text value (single line) | | `'text'` | `string` | A longer text value (multi-line, rendered as a textarea in Cloud) | | `'number'` | `number` | A numeric value | | `'boolean'` | `boolean` | A true/false toggle | | `'secret'` | `string` | A sensitive value like an API key or token. Masked in the Cloud dashboard. **Cannot be `isPublic`.** | > [!WARNING] > > Config values with `type: 'secret'` cannot have `isPublic: true`. Modelence > will throw an error at startup if this rule is violated. ## Reading Config Values ### Server-side Call `getConfig` directly on the module instance. The return type is inferred automatically from the schema — no casts needed: `Module.getConfig()` is available since `modelence@0.15.0`. ```typescript title="src/server/payments/index.ts" theme={null} import { Module } from 'modelence/server'; const paymentsModule = new Module('payments', { configSchema: { apiKey: { type: 'secret', default: '', isPublic: false }, maxRetries: { type: 'number', default: 3, isPublic: false }, }, mutations: { async charge({ amount }) { const apiKey = paymentsModule.getConfig('apiKey'); // string const retries = paymentsModule.getConfig('maxRetries'); // number // ... }, }, }); export default paymentsModule; ``` ### Client-side Use `createClientModule` to create a typed accessor for a module's public config values. Pass the module type via `import type` — no server code is bundled on the client. `createClientModule(...).getConfig()` is available since `modelence@0.15.0`. ```typescript title="src/client/payments.ts" theme={null} import type paymentsModule from '../server/payments'; import { createClientModule } from 'modelence/client'; export const payments = createClientModule('payments'); ``` ```typescript title="src/components/Checkout.tsx" theme={null} import { payments } from '../client/payments'; function Checkout() { const currency = payments.getConfig('currency'); // string | undefined return
Currency: {currency}
; } ``` Only values marked `isPublic: true` are available on the client. Private and `secret` values are **not** sent to the client and will not appear as valid keys. For typed query and mutation wrappers, see: * [Queries](/core-concepts/queries) * [Mutations](/core-concepts/mutations) ## Managing Values in Modelence Cloud Once your module defines a `configSchema`, the configuration fields appear automatically in the Modelence Cloud dashboard: 1. Go to [cloud.modelence.com](https://cloud.modelence.com) 2. Select your environment 3. Open the **Application** tab 4. Find your module's configuration section 5. Set values and save Changes sync to your running application automatically (within \~10 seconds). > [!TIP] > > Config values set in Modelence Cloud take precedence over defaults defined in > your code. Environment variables take precedence over both. ## Examples ### Storing a third-party API key ```typescript title="src/server/ai/index.ts" theme={null} import { Module } from 'modelence/server'; const aiModule = new Module('ai', { configSchema: { apiKey: { type: 'secret', default: '', isPublic: false, }, model: { type: 'string', default: 'gpt-4o', isPublic: false, }, }, mutations: { async generateResponse({ prompt }: { prompt: string }) { const apiKey = aiModule.getConfig('apiKey'); // string const model = aiModule.getConfig('model'); // string if (!apiKey) { throw new Error('AI API key not configured'); } const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model, messages: [{ role: 'user', content: prompt }], }), }); return response.json(); }, }, }); export default aiModule; ``` ### Feature toggle with a boolean config ```typescript title="src/server/notifications/index.ts" theme={null} import { Module } from 'modelence/server'; const notificationsModule = new Module('notifications', { configSchema: { emailEnabled: { type: 'boolean', default: true, isPublic: false, }, footer: { type: 'text', default: 'You are receiving this because you signed up for our service.', isPublic: false, }, }, mutations: { async sendNotification({ userId, message }: { userId: string; message: string }) { const emailEnabled = notificationsModule.getConfig('emailEnabled'); // boolean if (!emailEnabled) { return { skipped: true }; } const footer = notificationsModule.getConfig('footer'); // string // Send email with message + footer... }, }, }); export default notificationsModule; ``` ### Exposing config to the client ```typescript title="src/server/app/index.ts" theme={null} import { Module } from 'modelence/server'; export default new Module('app', { configSchema: { appName: { type: 'string', default: 'My App', isPublic: true, }, maintenanceMode: { type: 'boolean', default: false, isPublic: true, }, }, }); ``` ```typescript title="src/client/app.ts" theme={null} import type appModule from '../server/app'; import { createClientModule } from 'modelence/client'; export const app = createClientModule('app'); ``` ```typescript title="src/components/Header.tsx" theme={null} import { app } from '../client/app'; function Header() { const appName = app.getConfig('appName'); // string | undefined const maintenance = app.getConfig('maintenanceMode'); // boolean | undefined if (maintenance) { return
We are currently undergoing maintenance. Please check back soon.
; } return

{appName}

; } ``` ## Type Reference See the full API reference for config types: * [`ConfigSchema`](/api-reference/modelence/index/type-aliases/ConfigSchema) — The schema object passed to a module * [`ConfigType`](/api-reference/modelence/server/type-aliases/ConfigType) — The union of allowed type values * [`getConfig` (server)](/api-reference/modelence/server/functions/getConfig) — Read config on the server (untyped, for dynamic keys) * [`getConfig` (client)](/api-reference/modelence/client/functions/getConfig) — Read config on the client (untyped, for dynamic keys) # Environment & Setup Source: https://docs.modelence.com/core-concepts/environment-and-setup Modelence provides flexible configuration options for your application. You can configure your app through the `startApp()` function, environment variables, and Modelence Cloud settings. ## Configuration Methods There are three ways to configure your Modelence application, listed in order of precedence: 1. **Environment Variables** - Highest priority, overrides everything 2. **Modelence Cloud** - Synced configuration from cloud.modelence.com 3. **startApp() Options** - Direct code configuration, lowest priority > [!TIP] > > Environment variables always take precedence, allowing you to override any configuration when deploying to different environments. ## Basic Configuration with startApp() The `startApp()` function is your application's entry point where you configure core settings: ```typescript title="src/server/app.ts" theme={null} import { startApp } from 'modelence/server'; import todoModule from './todo'; import userModule from './users'; startApp({ // Register your modules modules: [todoModule, userModule], // Email configuration email: { provider: resendProvider, from: 'noreply@yourapp.com' } }); ``` ## Environment Variables Environment variables provide a way to configure your application without hardcoding values. They override all other configuration methods. ### Core Environment Variables ```env title=".modelence.env" theme={null} # MongoDB connection string MONGODB_URI="mongodb+srv://user:pass@cluster.mongodb.net/myapp" # Server configuration PORT=3000 MODELENCE_SITE_URL=http://localhost ``` ### All Environment Variables Every `MODELENCE_*` variable (plus the few non-prefixed ones) that the framework or first-party packages read. Anything not listed here is application-specific and should go through `defineConfigs` / `getConfig` instead. #### Core | Variable | Type | Default | Consumed by | | - | - | - | - | | `MONGODB_URI` | string | — | `packages/modelence` (database connection) | | `MONGODB_POOL_SIZE` | number | driver default | `packages/modelence` (pool size override) | | `MODELENCE_SITE_URL` | string | — | `packages/modelence` (public site URL, used by auth callbacks and emails) | | `PORT` | number | `3000` | `packages/modelence/app/server.ts` | | `MODELENCE_PORT` | number | falls back to `PORT` | `packages/modelence/app/server.ts` | | `MODELENCE_TRUSTED_PROXIES` | string (comma-separated addresses/ranges) | all proxies trusted for backward compatibility | `packages/modelence/app/server.ts` | | `NODE_ENV` | `development` \| `production` | `development` | Build pipeline, cookie `secure` flag, Vite dev server | | `MODELENCE_LOG_LEVEL` | `debug` \| `info` \| `warn` \| `error` | `info` | `packages/modelence/telemetry` | | `MODELENCE_ENV_TYPE` | string | — | `packages/modelence/config` (`_system.env.type`) | | `MODELENCE_MULTI_INSTANCE` | boolean | `false` | `packages/modelence/config` (`_system.multiInstance`) | #### Modelence Cloud | Variable | Type | Default | Consumed by | | - | - | - | - | | `MODELENCE_SERVICE_ENDPOINT` | string | `https://cloud.modelence.com` | `packages/modelence/app` (cloud API endpoint) | | `MODELENCE_SERVICE_TOKEN` | string | — | `packages/modelence/app/backendApi.ts` (cloud auth token, written by `setup --token`) | | `MODELENCE_CONTAINER_ID` | string | — | `packages/modelence/app/backendApi.ts` (assigned per running container) | | `MODELENCE_ENVIRONMENT_ID` | string | — | `packages/modelence/app` (cloud environment binding) | | `MODELENCE_TRACKING_ENABLED` | boolean | `true` | `packages/modelence/app` (set to `false` to opt out of tracking) | #### Authentication (OAuth providers) | Variable | Type | Default | Consumed by | | - | - | - | - | | `MODELENCE_AUTH_GOOGLE_ENABLED` | boolean | `false` | `packages/modelence/auth/providers/google.ts` | | `MODELENCE_AUTH_GOOGLE_CLIENT_ID` | string | — | `packages/modelence/auth/providers/google.ts` | | `MODELENCE_AUTH_GOOGLE_CLIENT_SECRET` | string | — | `packages/modelence/auth/providers/google.ts` | | `MODELENCE_AUTH_GITHUB_ENABLED` | boolean | `false` | `packages/modelence/auth/providers/github.ts` | | `MODELENCE_AUTH_GITHUB_CLIENT_ID` | string | — | `packages/modelence/auth/providers/github.ts` | | `MODELENCE_AUTH_GITHUB_CLIENT_SECRET` | string | — | `packages/modelence/auth/providers/github.ts` | | `MODELENCE_AUTH_GITHUB_CLIENT_SCOPES` | string (comma-separated) | `read:user,user:email` | `packages/modelence/auth/providers/github.ts` | | `MODELENCE_AUTH_MOBILE_REDIRECT_URLS` | string (comma-separated) | — | `packages/modelence/auth/providers/mobileRedirect.ts` (deep links native OAuth may return to, e.g. `myapp://auth`; merged with `auth.mobile.redirectUrls`) | #### Email providers | Variable | Type | Default | Consumed by | | - | - | - | - | | `MODELENCE_EMAIL_RESEND_API_KEY` | string | — | `@modelence/resend` | | `MODELENCE_EMAIL_AWS_SES_REGION` | string | — | `@modelence/aws-ses` | | `MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID` | string | — | `@modelence/aws-ses` | | `MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY` | string | — | `@modelence/aws-ses` | | `MODELENCE_EMAIL_SMTP_HOST` | string | — | `@modelence/smtp` | | `MODELENCE_EMAIL_SMTP_PORT` | number | — | `@modelence/smtp` | | `MODELENCE_EMAIL_SMTP_USER` | string | — | `@modelence/smtp` | | `MODELENCE_EMAIL_SMTP_PASS` | string | — | `@modelence/smtp` | > [!TIP] > > Any variable not listed here is application-specific. Define it through your modules' `configSchema` so Modelence Cloud can manage it and `getConfig()` can read it type-safely. ## Modelence Cloud Configuration On Modelence Cloud, the environment's variables and its `configSchema` values reach the app when it starts, both when it is deployed and when it runs locally in a connected environment. See [Environment Variables](/cloud/environment-variables) for what the platform provides and how variables are declared, and [Local Setup](/setup) for connecting a project on your machine. ## Next Steps > [card] [Authentication](/authentication/index) > > Configure authentication and user management > [card] [Email Setup](/email) > > Set up email providers for transactional emails > [card] [Roles & Permissions](/roles) > > Define user roles and permissions > [card] [WebSockets](/websockets) > > Enable real-time communication # Migrations Source: https://docs.modelence.com/core-concepts/migrations Migrations let you run one-time tasks safely on application startup — such as evolving database schemas, backfilling data, or initializing external services like Stripe plans. ## Defining Migrations Pass a `migrations` array to `startApp()`. Each migration has: * `version` - Unique numeric version * `description` - Human-readable summary * `handler` - Async function that performs the task Define each migration handler in its own file under a `migrations/` directory, then wire up versions and descriptions in the index file: ```typescript title="src/server/migrations/backfill-todo-status.ts" theme={null} import { dbTodos } from '../todo/db'; export async function backfillTodoStatus() { await dbTodos.updateMany( { status: { $exists: false } }, { $set: { status: 'open' } } ); return 'Backfilled todos without status'; } ``` ```typescript title="src/server/migrations/index.ts" theme={null} import { backfillTodoStatus } from './backfill-todo-status'; export const migrations = [ { version: 1, description: 'Backfill status field on existing todos', handler: backfillTodoStatus, }, ]; ``` ```typescript title="src/server/app.ts" theme={null} import { startApp } from 'modelence/server'; import todoModule from './todo'; import { migrations } from './migrations'; startApp({ modules: [todoModule], migrations, }); ``` ## How Migrations Run On application startup, Modelence will: 1. Acquire a distributed `migrations` lock. If another instance already owns it, this instance skips running migrations. 2. Read existing migration versions from the `_modelenceMigrations` collection. 3. Run only pending migration versions from your `migrations` array. 4. Write a record to `_modelenceMigrations` with: * `version` * `status` (`completed` or `failed`) * `description` * `output` (handler result or error message) * `appliedAt` 5. Release the lock. > [!NOTE] > > Migrations run in the order they appear in your `migrations` array, so keep > that array intentionally ordered and use unique versions. > [!NOTE] > > Store indexes run before migrations with this startup behavior: > > * Stores using `indexCreationMode: 'blocking'` are awaited before migrations begin. Use this for small collections with critical index dependencies (e.g. unique indexes that a migration relies on). > * Stores using `indexCreationMode: 'background'` may still be creating indexes while migrations run. Prefer this for large collections to avoid blocking app startup. > > See [Indexes: Index Creation Mode](/indexes#index-creation-mode) for configuration details. ## Migrations and Cron Jobs > [!WARNING] > > Migration execution is scheduled asynchronously at startup, and cron jobs are > started right after. This means migration handlers and cron handlers can run in > parallel, so design both to be safe under race conditions. Recommended approach: * Make migration handlers idempotent (safe to run once or be retried manually). * Use conditional updates (for example, update only documents missing the new field). * Keep cron handlers compatible with both pre-migration and post-migration data during rollout windows. * If a cron job strictly depends on a migration, add an explicit readiness guard in the cron handler. Example of a race-safe migration pattern: ```typescript theme={null} await dbTodos.updateMany( { status: { $exists: false } }, { $set: { status: 'open' } } ); ``` ## Failure Behavior Failed migrations are recorded with `status: 'failed'`. Since version tracking is version-based, a failed version is still considered already seen on future starts — it will **not** be retried automatically on the next boot. If you need to rerun logic, prefer creating a new migration version. Edit a previous version's handler only if the migration has never run successfully in any environment. ### No Built-in Rollback Modelence migrations are forward-only. There is no `down` handler, no auto-revert on failure, and no CLI command to roll back. Failed handlers do **not** un-do partial writes — design each handler to be idempotent so a rerun (after manual cleanup) converges on the desired state. Practical guidance: * Use conditional updates (e.g. `{ field: { $exists: false } }`) so partial progress is safe to resume. * Avoid destructive operations (drops, deletes) inside the same migration that performs the new write. Split them into separate versions and only run the destructive step after verifying the prior version succeeded everywhere. * Wrap multi-document changes in your own checkpoint logic if you need to resume after a crash mid-handler — the runner itself records only the final outcome per version. ### Manual Cleanup of `_modelenceMigrations` To force a version to rerun, delete (or update) its document in the `_modelenceMigrations` collection before restarting the app. Each document has the shape: ```typescript theme={null} { version: number; // unique status: 'completed' | 'failed'; description?: string; output?: string; // handler return value or error message (max ~15MB) appliedAt: Date; } ``` To rerun a failed `version: 7` migration: ```javascript theme={null} // mongo shell or Compass db._modelenceMigrations.deleteOne({ version: 7 }); ``` On the next startup the runner sees no record for version 7 and re-executes the handler. Do this only when you are sure the prior partial run is safe to re-apply, or you have manually undone its effects first. ### CLI Surface Migrations are run **only at application startup**. There is currently no `modelence migrate` CLI command, no dry-run mode, and no way to invoke a single migration handler out-of-band. To run or re-run migrations you must (re)start the app — typically by deploying a new version that includes the new entries in your `migrations` array. # Modules Source: https://docs.modelence.com/core-concepts/modules Organize your backend into self-contained units with queries, mutations, stores, and configuration Modules are the fundamental building blocks of a Modelence application. They help you organize your backend functionality into cohesive, self-contained units that encapsulate queries, mutations, stores, and configuration. ## What is a Module? A Module in Modelence is similar to a feature module in other frameworks. It groups related functionality together, making your codebase more maintainable and easier to reason about. ```typescript theme={null} import { Module } from 'modelence/server'; export default new Module('todo', { // Module configuration goes here }); ``` ## Module Structure A typical module includes: * **Stores** - MongoDB collection definitions * **Queries** - Read operations that fetch data * **Mutations** - Write operations that modify data * **Configuration** - Module-specific settings * **Cron Jobs** - Scheduled tasks (optional) > [!NOTE] > > Data migrations are configured at the `startApp()` level (not inside individual > modules). See the [Migrations documentation](/core-concepts/migrations). ## Stores Stores define your MongoDB collections with schemas, indexes, and custom methods. Including stores in your module ensures they're automatically provisioned when the server starts. ```typescript theme={null} import { Store, schema } from 'modelence/server'; export const dbTodos = new Store('todos', { schema: { title: schema.string(), isCompleted: schema.boolean(), userId: schema.userId(), createdAt: schema.date() }, indexes: [ { key: { userId: 1 } } ] }); export default new Module('todo', { // Register the store with the module stores: [dbTodos], queries: { async getAll({}, { user }) { return await dbTodos.fetch({ userId: user.id }); } } }); ``` > [!TIP] > > Learn more about working with Stores in the [Stores documentation](/stores). ## Authentication & Authorization > [!WARNING] > > Every query and mutation you define is publicly callable over the network. > There is no declarative `auth` or `authorize` option on a method definition — > authentication and authorization must be enforced inside the handler. Read `user` from the handler context and check it explicitly. For an unauthenticated caller, `user` is `null`: ```typescript theme={null} import { Module, ObjectId } from 'modelence/server'; import { AuthError } from 'modelence'; import { dbTodos } from './db'; export default new Module('todo', { queries: { // Requires a signed-in user async getAll({}, { user }) { if (!user) { throw new AuthError('Not authenticated'); } return await dbTodos.fetch({ userId: user.id }); }, // Public: no user check async getPublic() { return await dbTodos.fetch({ isPublic: true }); } }, mutations: { // Admin only async adminDelete({ id }, { user }) { if (!user) { throw new AuthError('Not authenticated'); } // Throws if the user doesn't have the "admin" role user.requireRole('admin'); return await dbTodos.deleteOne({ _id: new ObjectId(id) }); } } }); ``` > [!TIP] > > See [Roles](/roles) for defining roles, assigning them to users, and using > `user.hasRole` / `user.requireRole`. ## Queries Queries are read operations that fetch data without modifying state. For full query patterns, including client usage with `callMethod`, `modelenceQuery`, and typed client modules, see [Queries](/core-concepts/queries). ## Mutations Mutations are write operations that create, update, or delete data. For full mutation patterns, including client usage with `callMethod`, `modelenceMutation`, and typed client modules, see [Mutations](/core-concepts/mutations). ## Rate Limiting Protect your queries and mutations from abuse by declaring rate limit rules on the module and consuming them inside handlers: ```typescript theme={null} import { Module, consumeRateLimit } from 'modelence/server'; import { time } from 'modelence/server'; export default new Module('todo', { rateLimits: [ { bucket: 'todoCreate', type: 'ip', window: time.minutes(1), limit: 10 }, ], mutations: { async create({ title }, { user, connectionInfo }) { await consumeRateLimit({ bucket: 'todoCreate', type: 'ip', value: connectionInfo.ip, message: 'Too many todos created. Please slow down.', }); const { insertedId } = await dbTodos.insertOne({ title, userId: user.id, isCompleted: false, createdAt: new Date() }); return insertedId; } } }); ``` > [!TIP] > > Learn more about rate limiting in the [Custom Rate Limiting documentation](/rate-limiting). ## Best Practices ### 1. Keep Modules Focused Each module should represent a single domain or feature: ```typescript theme={null} // Good: Focused todo module export default new Module('todo', { // Only todo-related functionality }); // Good: Separate user module export default new Module('users', { // Only user-related functionality }); ``` ### 2. Use Clear Naming Name your queries and mutations descriptively: ```typescript theme={null} // Good queries: { getAll() { }, getByStatus({ status }) { }, getOverdue() { } } // Avoid queries: { get() { }, // Too generic fetchData() { }, // Unclear what data q1() { } // Meaningless name } ``` ### 3. Handle Errors Gracefully Always handle potential errors and provide meaningful messages: ```typescript theme={null} mutations: { async delete({ id }, { user }) { const todo = await dbTodos.findById(id); if (!todo) { throw new Error('Todo not found'); } if (todo.userId !== user.id) { throw new Error('Not authorized to delete this todo'); } return await dbTodos.deleteOne({ _id: new ObjectId(id) }); } } ``` ### 4. Keep Business Logic in Modules Don't put business logic directly in your database stores. Keep it in your module methods: ```typescript theme={null} // Good: Business logic in module export default new Module('todo', { mutations: { async complete({ id }, { user }) { const todo = await dbTodos.findById(id); // Business logic if (todo.isCompleted) { throw new Error('Todo is already completed'); } await dbTodos.updateOne(id, { $set: { isCompleted: true, completedAt: new Date() } }); // Trigger side effects await callMethod('notifications.send', { userId: user.id, message: 'Todo completed!' }); } } }); ``` ### 5. Validate Method Arguments Method arguments arrive from the client untyped and unvalidated — there is no `input` option on a method definition. Parse them at the top of the handler to get validation and types in one step: ```typescript theme={null} import { Module, schema } from 'modelence/server'; import { AuthError } from 'modelence'; const createArgs = schema.object({ title: schema.string().min(1), priority: schema.enum(['low', 'medium', 'high']) }); export default new Module('todo', { mutations: { async create(args, { user }) { if (!user) { throw new AuthError('Not authenticated'); } // Throws on invalid input; `input` is fully typed from here on const input = createArgs.parse(args); const { insertedId } = await dbTodos.insertOne({ ...input, userId: user.id, createdAt: new Date() }); return insertedId; } } }); ``` ## Next Steps > [card] [Queries](/core-concepts/queries) > > Learn how to define and call query methods > [card] [Mutations](/core-concepts/mutations) > > Learn how to define and call mutation methods > [card] [Migrations](/core-concepts/migrations) > > Learn how migration scripts run and how to handle cron race conditions > [card] [Configuration](/configuration) > > Learn about configuration options > [card] [Stores](/stores) > > Deep dive into working with MongoDB stores # Mutations Source: https://docs.modelence.com/core-concepts/mutations Define mutation methods and call them from the client with callMethod, modelenceMutation, or createClientModule. Typed client modules are available since modelence@0.15.0. Mutations are write operations that create, update, or delete data. They are similar to `POST`, `PUT`, and `DELETE` endpoints in REST. ## Version Requirements Typed client modules for mutations require: * `createClientModule(...).mutation()` - available since `modelence@0.15.0` ## Defining Mutations Define mutations inside a module's `mutations` object: ```typescript theme={null} import { Module, ObjectId } from 'modelence/server'; import { dbTodos } from './db'; export default new Module('todo', { mutations: { // Create a new todo async create({ title, dueDate }, { user }) { const { insertedId } = await dbTodos.insertOne({ title, dueDate, userId: user.id, isCompleted: false, createdAt: new Date(), }); return insertedId; }, // Update a todo async update({ id, title, isCompleted }) { return await dbTodos.updateOne( id, { $set: { title, isCompleted } } ); }, // Delete a todo async delete({ id }) { return await dbTodos.deleteOne({ _id: new ObjectId(id) }); }, }, }); ``` ## Calling Mutations from the Client ### `callMethod` ```typescript theme={null} import { callMethod } from 'modelence/client'; const todoId = await callMethod('todo.create', { title: 'Buy groceries', dueDate: new Date('2024-12-31'), }); ``` ### `modelenceMutation` (TanStack Query) ```typescript theme={null} import { useMutation, useQueryClient } from '@tanstack/react-query'; import { modelenceMutation } from 'modelence/client'; function CreateTodo() { const queryClient = useQueryClient(); const { mutate: createTodo } = useMutation({ ...modelenceMutation('todo.create'), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['todo.getAll'] }); }, }); const handleSubmit = () => { createTodo({ title: 'New todo', dueDate: new Date() }); }; return ; } ``` ### `createClientModule(...).mutation()` (typed client modules) `createClientModule(...).mutation()` is available since `modelence@0.15.0`. ```typescript title="src/server/admin/index.ts" theme={null} import { Module } from 'modelence/server'; export default new Module('admin', { mutations: { async inviteUser({ email }: { email: string }) { // returns { success: boolean } }, }, }); ``` ```typescript title="src/client/admin.ts" theme={null} import type adminModule from '../server/admin'; import { createClientModule } from 'modelence/client'; export const admin = createClientModule('admin'); ``` ```typescript title="src/components/AdminPanel.tsx" theme={null} import { useMutation } from '@tanstack/react-query'; import { admin } from '../client/admin'; function AdminPanel() { const { mutate: invite } = useMutation(admin.mutation('inviteUser')); return ; } ``` ## Related * [Queries](/core-concepts/queries) * [Modules](/core-concepts/modules) # Project Structure Source: https://docs.modelence.com/core-concepts/project-structure A Modelence project follows a well-organized structure that clearly separates client and server code, making it easy to build full-stack applications with TypeScript. ## Directory Overview When you create a new Modelence project, you'll see the following structure: ``` my-app/ ├── src/ │ ├── client/ # Frontend code │ ├── server/ # Backend code │ └── shared/ # (Optional) Shared code ├── assets/ # Static assets (images, fonts) ├── .modelence.env # Generated by `npx modelence@latest setup` (cloud connection) ├── package.json # Project dependencies └── tsconfig.json # TypeScript configuration ``` ## Client Directory The `src/client` directory contains all your frontend React application code. ### Key Files * **`index.html`** - The main HTML template for your application. You typically don't need to modify this file unless you want to add meta tags, external scripts, or customize the root template. * **`index.tsx`** - The React application entry point. This is where you initialize your client-side app using `renderApp()` and configure providers. ```typescript theme={null} import { renderApp } from 'modelence/client'; import routes from './routes'; import './index.css'; renderApp({ routes, }); ``` * **`index.css`** - Global CSS styles for your application. This file typically includes Tailwind CSS imports and any global style customizations. * **`routes.ts`** - Client-side routing configuration that maps URL paths to React components. ```typescript theme={null} import { createBrowserRouter } from 'react-router-dom'; import Home from './pages/Home'; import About from './pages/About'; export default createBrowserRouter([ { path: '/', element: }, { path: '/about', element: }, ]); ``` ### Organizing Client Code Within the `client` directory, you can organize your code into subdirectories: ``` src/client/ ├── components/ # Reusable React components ├── pages/ # Page-level components ├── hooks/ # Custom React hooks └── utils/ # Client-side utilities ``` ## Server Directory The `src/server` directory contains all your backend code, including API logic, database models, and business logic. ### Key Files * **`app.ts`** - The server entry point where you configure and start your Modelence application. ```typescript theme={null} import { startApp } from 'modelence/server'; import todoModule from './todo'; startApp({ modules: [todoModule], }); ``` ### Organizing Server Code by Modules The recommended approach is to organize server code into **modules** - self-contained units of functionality: ``` src/server/ ├── migrations/ # (Optional) App migration scripts │ ├── index.ts # Exports the ordered migrations array │ └── ... # One file per migration handler ├── todo/ │ ├── index.ts # Module definition │ ├── db.ts # Database stores │ └── utils.ts # Module utilities ├── users/ │ ├── index.ts │ └── db.ts └── app.ts # Main server file ``` Each module typically contains: * **Module definition** - Queries, mutations, and configuration * **Database stores** - MongoDB collection definitions * **Business logic** - Domain-specific utilities and helpers For data evolution over time, keep app-level migration scripts under `src/server/migrations/` — one file per handler, with `index.ts` exporting the ordered array passed to `startApp({ migrations })`. See [Migrations](/core-concepts/migrations) for the full layout. > [!TIP] > > Grouping code by modules (domains/features) rather than by type (controllers, models, etc.) makes your codebase more maintainable and easier to understand as it grows. ## Shared Code You can create a `src/shared` directory (or any other name) for code that needs to be used by both client and server: ``` src/ ├── client/ ├── server/ └── shared/ ├── types.ts # Shared TypeScript types ├── constants.ts # Shared constants └── utils.ts # Shared utilities ``` > [!WARNING] > > Be careful when importing server code into client code or vice versa. ## Configuration Files ### .modelence.env Environment-specific configuration for your application. This file should never be committed to version control. ```env theme={null} # MongoDB connection MONGODB_URI="mongodb+srv://..." # Other configuration PORT=3000 ``` > [!WARNING] > > Always add `.modelence.env` to your `.gitignore` file to prevent committing sensitive credentials. ### package.json Standard Node.js package configuration. Modelence projects include these key scripts: ```json theme={null} { "scripts": { "dev": "modelence dev", "build": "modelence build", "start": "node dist/server/app.js" } } ``` ### tsconfig.json TypeScript configuration for your project. Modelence sets up appropriate defaults for both client and server code with path aliases and module resolution. ## Build Output When you build your application with `npm run build`, Modelence generates a `dist` directory: ``` dist/ ├── client/ # Built frontend assets │ ├── index.html │ ├── assets/ │ └── ... └── server/ # Compiled server code └── app.js ``` The built application is ready for deployment to any Node.js hosting platform. ## Next Steps > [card] [Modules](/core-concepts/modules) > > Learn how to organize your application logic into modules > [card] [Configuration](/configuration) > > Understand how to configure your Modelence application # Queries Source: https://docs.modelence.com/core-concepts/queries Define query methods and call them from the client with callMethod, modelenceQuery, or createClientModule. Typed client modules are available since modelence@0.15.0. Queries are read operations that retrieve data without modifying state. They are similar to `GET` endpoints in REST. ## Version Requirements Typed client modules for queries require: * `createClientModule(...).query()` - available since `modelence@0.15.0` ## Defining Queries Define queries inside a module's `queries` object: ```typescript theme={null} import { Module } from 'modelence/server'; import { dbTodos } from './db'; export default new Module('todo', { queries: { // Get a single todo by ID async getOne({ id }) { return await dbTodos.findById(id); }, // Get all todos for the current user async getAll({}, { user }) { return await dbTodos.fetch({ userId: user.id }); }, // Get todos with filtering async getCompleted({}, { user }) { return await dbTodos.fetch({ userId: user.id, isCompleted: true, }); }, }, }); ``` ## Query Parameters Queries receive two arguments: 1. **Input parameters** - data passed from the client. 2. **Context** - server-side context including: * `user` - current authenticated user (if logged in) * `req` - Express request object * `res` - Express response object ## Calling Queries from the Client ### `callMethod` ```typescript theme={null} import { callMethod } from 'modelence/client'; const todos = await callMethod('todo.getAll'); const todo = await callMethod('todo.getOne', { id: '123' }); ``` ### `modelenceQuery` (TanStack Query) ```typescript theme={null} import { useQuery } from '@tanstack/react-query'; import { modelenceQuery } from 'modelence/client'; function TodoList() { const { data: todos } = useQuery(modelenceQuery('todo.getAll')); return
{/* render todos */}
; } ``` > [!NOTE] > > Since `modelence@0.15.0`, the query helpers (`modelenceQuery`, > `modelenceLiveQuery`, `modelenceMutation`, `createQueryKey`) are available > directly from `modelence/client` — this is the recommended import. The > `@modelence/react-query` package still exports the same helpers and continues to > work, but new code should import from `modelence/client`. See > [Migrating from @modelence/react-query](/live-queries#migrating-from-modelence-react-query). ### `createClientModule(...).query()` (typed client modules) `createClientModule(...).query()` is available since `modelence@0.15.0`. ```typescript title="src/server/admin/index.ts" theme={null} import { Module } from 'modelence/server'; export default new Module('admin', { queries: { async getUsers({ page }: { page: number }) { // returns User[] }, }, }); ``` ```typescript title="src/client/admin.ts" theme={null} import type adminModule from '../server/admin'; import { createClientModule } from 'modelence/client'; export const admin = createClientModule('admin'); ``` ```typescript title="src/components/AdminPanel.tsx" theme={null} import { useQuery } from '@tanstack/react-query'; import { admin } from '../client/admin'; function AdminPanel() { const { data: users } = useQuery(admin.query('getUsers', { page: 1 })); return
{/* render users */}
; } ``` ## Related * [Mutations](/core-concepts/mutations) * [Modules](/core-concepts/modules) # MongoDB Data API Source: https://docs.modelence.com/data-api REST API for MongoDB operations with Modelence > [!TIP] > > **Quick Start Tutorial**: [Migrate your MongoDB Data API in 30 minutes](https://medium.com/modelence/migrate-your-mongodb-data-api-in-30-minutes-c1d8d5959728) - A step-by-step guide to get started with Modelence Data API. ## What is MongoDB Data API An open-source API to read, write, and aggregate data in MongoDB. The application can be deployed to Modelence Cloud or to any other cloud provider. * **CRUD Operations**: Insert, find, update, and delete documents * **Advanced Querying**: Aggregation pipelines and complex queries * **Database Management**: Collection and index management * **Authentication**: API key-based security * **MongoDB Operations**: Direct access to MongoDB features ## Project Setup ### 1. Create a new application ```bash theme={null} npx degit modelence/examples/data-api data-api cd data-api npm install ``` ### 2. Connect to Modelence Cloud 1. Open [cloud.modelence.com](https://cloud.modelence.com/) create 2. Create a new application and a local environment 3. Click on Setting → Set up 4. Follow the steps described in the modal ### 3. Start the Development Server ```bash theme={null} npx modelence@latest dev ``` Your Data API will be available at `http://localhost:3000` ### 4. Deploy to Modelence Cloud To deploy your Data API to cloud: 1. **Create a Cloud Environment**: In your Modelence Cloud dashboard, navigate to your application and create a new environment, selecting **cloud** as the environment type. 2. **Get the Deployment Command**: Go to your cloud environment's settings page and copy the deployment command: ```bash theme={null} npx modelence@latest deploy --app --env ``` The browser opens with that environment preselected; confirm it there to start the deploy. 3. **Deploy**: Run the deployment command in your project directory. The deployment process will: * Build your application * Upload it to Modelence Cloud * Provision resources including MongoDB database and server infrastructure * Launch your application Once deployment completes, your environment status will become `active` and you'll receive a URL to access your deployed Data API. ## Core Components ### DB Access MongoDB is configured when you create an environment. During environment creation, you can choose to: * Create a new MongoDB database, or * Connect to an existing MongoDB instance ### Authentication The Data API supports two authentication methods: #### 1. Direct API Key Authentication Set the api key as the value of `dataApi.apiKey` in Modelence Cloud from the Application page. (Alternatively you can use the `DATA_API_KEY` environment variable). Use the `apiKey` header in your requests: ```bash theme={null} apiKey: your-secure-api-key-here ``` #### 2. Bearer Token Authentication Alternatively, you can use Bearer token authentication by first obtaining an access token from the login endpoint: **Login Endpoint**: `POST /auth/providers/api-key/login` **Request**: ```json theme={null} { "key": "your-api-key" } ``` **Response**: ```json theme={null} { "access_token": "eyJhbGc...", "refresh_token": "eyJhbGc...", "token_type": "Bearer", "expires_in": 1800 } ``` Then use the access token in the `Authorization` header: ```bash theme={null} Authorization: Bearer eyJhbGc... ``` Access tokens expire after 30 minutes. Use the refresh token to obtain a new access token without re-authenticating. ### Available Endpoints The API provides comprehensive MongoDB operations with full request/response specifications: ## API Operations Reference ### 1. Find One Document (`POST /data/v1/action/findOne`) **Purpose**: Retrieve a single document from a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name (uses default if not specified) "filter": {}, // Optional: Query filter object "projection": {} // Optional: Fields to include/exclude } ``` **Example Request**: ```json theme={null} { "collection": "users", "filter": { "email": "user@example.com" }, "projection": { "name": 1, "email": 1, "_id": 0 } } ``` **Response**: ```json theme={null} { "document": { "name": "John Doe", "email": "user@example.com" } } ``` ### 2. Find Multiple Documents (`POST /data/v1/action/find`) **Purpose**: Retrieve multiple documents from a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "filter": {}, // Optional: Query filter object "projection": {}, // Optional: Fields to include/exclude "sort": {}, // Optional: Sort specification "limit": 0, // Optional: Maximum number of documents "skip": 0 // Optional: Number of documents to skip } ``` **Example Request**: ```json theme={null} { "collection": "products", "filter": { "category": "electronics", "price": { "$lt": 500 } }, "projection": { "name": 1, "price": 1, "category": 1 }, "sort": { "price": 1 }, "limit": 10, "skip": 0 } ``` **Response**: ```json theme={null} { "documents": [ { "name": "Wireless Mouse", "price": 29.99, "category": "electronics" }, { "name": "USB Cable", "price": 9.99, "category": "electronics" } ] } ``` ### 3. Insert One Document (`POST /data/v1/action/insertOne`) **Purpose**: Insert a single document into a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "document": {} // Required: Document to insert } ``` **Example Request**: ```json theme={null} { "collection": "users", "document": { "name": "John Doe", "email": "john@example.com", "age": 30, "createdAt": "2024-01-01T00:00:00Z" } } ``` **Response**: ```json theme={null} { "insertedId": "507f1f77bcf86cd799439011" } ``` ### 4. Insert Multiple Documents (`POST /data/v1/action/insertMany`) **Purpose**: Insert multiple documents into a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "documents": [] // Required: Array of documents to insert } ``` **Example Request**: ```json theme={null} { "collection": "orders", "documents": [ { "orderId": "ORD001", "customerId": "CUST123", "total": 99.99, "status": "pending" }, { "orderId": "ORD002", "customerId": "CUST456", "total": 149.99, "status": "completed" } ] } ``` **Response**: ```json theme={null} { "insertedIds": [ "507f1f77bcf86cd799439011", "507f1f77bcf86cd799439012" ] } ``` ### 5. Update One Document (`POST /data/v1/action/updateOne`) **Purpose**: Update a single document in a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "filter": {}, // Required: Query filter to match document "update": {}, // Required: Update operations "upsert": false // Optional: Create document if not found } ``` **Example Request**: ```json theme={null} { "collection": "users", "filter": { "email": "john@example.com" }, "update": { "$set": { "lastLogin": "2024-01-15T10:30:00Z" }, "$inc": { "loginCount": 1 } }, "upsert": false } ``` **Response**: ```json theme={null} { "matchedCount": 1, "modifiedCount": 1 } ``` ### 6. Update Multiple Documents (`POST /data/v1/action/updateMany`) **Purpose**: Update multiple documents in a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "filter": {}, // Required: Query filter to match documents "update": {}, // Required: Update operations "upsert": false // Optional: Create documents if not found } ``` **Example Request**: ```json theme={null} { "collection": "products", "filter": { "category": "electronics" }, "update": { "$mul": { "price": 0.9 } }, "upsert": false } ``` **Response**: ```json theme={null} { "matchedCount": 25, "modifiedCount": 25 } ``` ### 7. Replace One Document (`POST /data/v1/action/replaceOne`) **Purpose**: Replace an entire document in a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "filter": {}, // Required: Query filter to match document "replacement": {}, // Required: New document to replace with "upsert": false // Optional: Create document if not found } ``` **Example Request**: ```json theme={null} { "collection": "users", "filter": { "_id": { "$oid": "507f1f77bcf86cd799439011" } }, "replacement": { "name": "Jane Smith", "email": "jane@example.com", "age": 25, "department": "Engineering" }, "upsert": false } ``` **Response**: ```json theme={null} { "matchedCount": 1, "modifiedCount": 1 } ``` ### 8. Delete One Document (`POST /data/v1/action/deleteOne`) **Purpose**: Delete a single document from a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "filter": {} // Required: Query filter to match document } ``` **Example Request**: ```json theme={null} { "collection": "users", "filter": { "email": "inactive@example.com" } } ``` **Response**: ```json theme={null} { "deletedCount": 1 } ``` ### 9. Delete Multiple Documents (`POST /data/v1/action/deleteMany`) **Purpose**: Delete multiple documents from a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "filter": {} // Required: Query filter to match documents } ``` **Example Request**: ```json theme={null} { "collection": "logs", "filter": { "timestamp": { "$lt": "2024-01-01T00:00:00Z" } } } ``` **Response**: ```json theme={null} { "deletedCount": 1523 } ``` ### 10. Aggregate (`POST /data/v1/action/aggregate`) **Purpose**: Perform aggregation operations on a collection **Request Fields**: ```json theme={null} { "collection": "string", // Required: Collection name "database": "string", // Optional: Database name "pipeline": [] // Required: Aggregation pipeline stages } ``` **Example Request**: ```json theme={null} { "collection": "orders", "pipeline": [ { "$match": { "status": "completed" } }, { "$group": { "_id": "$customerId", "totalSpent": { "$sum": "$total" }, "orderCount": { "$sum": 1 } } }, { "$sort": { "totalSpent": -1 } }, { "$limit": 10 } ] } ``` **Response**: ```json theme={null} { "documents": [ { "_id": "CUST123", "totalSpent": 1299.97, "orderCount": 13 }, { "_id": "CUST456", "totalSpent": 899.95, "orderCount": 6 } ] } ``` ### 11. Count Documents (`POST /data/v1/action/countDocuments`) **Purpose**: Count the number of documents matching a filter **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "filter": {} // Optional: Query filter object } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "users", "filter": { "status": "active" } } ``` **Response**: ```json theme={null} { "count": 1523 } ``` ### 12. Estimated Document Count (`POST /data/v1/action/estimatedDocumentCount`) **Purpose**: Get an estimated count of all documents in a collection (faster but less accurate than countDocuments) **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string" // Required: Database name } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "users" } ``` **Response**: ```json theme={null} { "count": 15432 } ``` ### 13. Distinct (`POST /data/v1/action/distinct`) **Purpose**: Get distinct values for a specific field across documents **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "key": "string", // Required: Field name to get distinct values for "filter": {} // Optional: Query filter object } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "orders", "key": "status", "filter": { "year": 2024 } } ``` **Response**: ```json theme={null} { "values": ["pending", "completed", "cancelled", "refunded"] } ``` ### 14. Find One and Update (`POST /data/v1/action/findOneAndUpdate`) **Purpose**: Find a single document and update it atomically, returning either the original or updated document **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "filter": {}, // Required: Query filter to match document "update": {}, // Required: Update operations (must contain update operators) "projection": {}, // Optional: Fields to include/exclude in returned document "sort": {}, // Optional: Sort specification if multiple documents match "upsert": false, // Optional: Create document if not found "returnNewDocument": true // Optional: Return updated document (true) or original (false) } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "inventory", "filter": { "sku": "ABC123" }, "update": { "$inc": { "quantity": -1 }, "$set": { "lastModified": "2024-01-15T10:30:00Z" } }, "returnNewDocument": true } ``` **Response**: ```json theme={null} { "document": { "_id": "507f1f77bcf86cd799439011", "sku": "ABC123", "quantity": 49, "lastModified": "2024-01-15T10:30:00Z" } } ``` ### 15. Find One and Replace (`POST /data/v1/action/findOneAndReplace`) **Purpose**: Find a single document and replace it entirely, returning either the original or replacement document **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "filter": {}, // Required: Query filter to match document "replacement": {}, // Required: New document (cannot contain update operators) "projection": {}, // Optional: Fields to include/exclude in returned document "sort": {}, // Optional: Sort specification if multiple documents match "upsert": false, // Optional: Create document if not found "returnNewDocument": true // Optional: Return replacement document (true) or original (false) } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "profiles", "filter": { "userId": "user123" }, "replacement": { "userId": "user123", "name": "Jane Doe", "email": "jane.doe@example.com", "preferences": { "theme": "dark", "notifications": true } }, "returnNewDocument": true } ``` **Response**: ```json theme={null} { "document": { "_id": "507f1f77bcf86cd799439011", "userId": "user123", "name": "Jane Doe", "email": "jane.doe@example.com", "preferences": { "theme": "dark", "notifications": true } } } ``` ### 16. Find One and Delete (`POST /data/v1/action/findOneAndDelete`) **Purpose**: Find a single document and delete it atomically, returning the deleted document **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "filter": {}, // Required: Query filter to match document "projection": {}, // Optional: Fields to include/exclude in returned document "sort": {} // Optional: Sort specification if multiple documents match } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "sessions", "filter": { "sessionId": "sess_abc123" }, "projection": { "userId": 1, "expiredAt": 1 } } ``` **Response**: ```json theme={null} { "document": { "_id": "507f1f77bcf86cd799439011", "userId": "user456", "expiredAt": "2024-01-15T10:30:00Z" } } ``` ### 17. Bulk Write (`POST /data/v1/action/bulkWrite`) **Purpose**: Perform multiple write operations (insert, update, replace, delete) in a single request **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "operations": [], // Required: Array of write operations "ordered": true // Optional: Execute operations in order (default true) } ``` **Operation Types**: * `insertOne`: `{ "insertOne": { "document": {...} } }` * `updateOne`: `{ "updateOne": { "filter": {...}, "update": {...}, "upsert": false } }` * `updateMany`: `{ "updateMany": { "filter": {...}, "update": {...}, "upsert": false } }` * `replaceOne`: `{ "replaceOne": { "filter": {...}, "replacement": {...}, "upsert": false } }` * `deleteOne`: `{ "deleteOne": { "filter": {...} } }` * `deleteMany`: `{ "deleteMany": { "filter": {...} } }` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "products", "operations": [ { "insertOne": { "document": { "name": "New Product", "price": 99.99 } } }, { "updateMany": { "filter": { "category": "electronics" }, "update": { "$mul": { "price": 0.9 } } } }, { "deleteOne": { "filter": { "discontinued": true } } } ], "ordered": true } ``` **Response**: ```json theme={null} { "insertedCount": 1, "matchedCount": 15, "modifiedCount": 15, "deletedCount": 1, "upsertedCount": 0, "upsertedIds": {} } ``` ### 18. Create Index (`POST /data/v1/action/createIndex`) **Purpose**: Create an index on a collection to improve query performance **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "keys": {}, // Required: Index specification (field: 1 or -1) "options": {} // Optional: Index options (name, unique, sparse, etc.) } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "users", "keys": { "email": 1 }, "options": { "name": "email_index", "unique": true, "sparse": false } } ``` **Response**: ```json theme={null} { "createdCollectionAutomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 } ``` ### 19. Drop Index (`POST /data/v1/action/dropIndex`) **Purpose**: Remove an index from a collection **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string", // Required: Database name "name": "string" // Required: Index name to drop } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "users", "name": "email_index" } ``` **Response**: ```json theme={null} { "nIndexesWas": 2, "ok": 1 } ``` ### 20. List Indexes (`POST /data/v1/action/listIndexes`) **Purpose**: List all indexes on a collection **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "collection": "string", // Required: Collection name "database": "string" // Required: Database name } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "users" } ``` **Response**: ```json theme={null} { "indexes": [ { "v": 2, "key": { "_id": 1 }, "name": "_id_" }, { "v": 2, "key": { "email": 1 }, "name": "email_index", "unique": true } ] } ``` ### 21. List Collections (`POST /data/v1/action/listCollections`) **Purpose**: List all collections in a database **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "database": "string" // Required: Database name } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb" } ``` **Response**: ```json theme={null} { "collections": [ { "name": "users", "type": "collection" }, { "name": "products", "type": "collection" }, { "name": "orders", "type": "collection" } ] } ``` ### 22. Create Collection (`POST /data/v1/action/createCollection`) **Purpose**: Create a new collection in a database **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "database": "string", // Required: Database name "collection": "string" // Required: Collection name to create } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "analytics" } ``` **Response**: ```json theme={null} { "ok": 1 } ``` ### 23. Drop Collection (`POST /data/v1/action/dropCollection`) **Purpose**: Delete a collection and all its documents **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "database": "string", // Required: Database name "collection": "string" // Required: Collection name to drop } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "collection": "temp_data" } ``` **Response**: ```json theme={null} { "ok": 1 } ``` ### 24. List Databases (`POST /data/v1/action/listDatabases`) **Purpose**: List all available databases **Request Fields**: ```json theme={null} { "dataSource": "string" // Required: Data source identifier } ``` **Example Request**: ```json theme={null} { "dataSource": "main" } ``` **Response**: ```json theme={null} { "databases": [ { "name": "admin", "sizeOnDisk": 32768, "empty": false }, { "name": "mydb", "sizeOnDisk": 8192000, "empty": false }, { "name": "test", "sizeOnDisk": 32768, "empty": true } ], "totalSize": 8256736, "ok": 1 } ``` ### 25. Run Command (`POST /data/v1/action/runCommand`) **Purpose**: Execute arbitrary database commands **Request Fields**: ```json theme={null} { "dataSource": "string", // Required: Data source identifier "database": "string", // Required: Database name "command": {} // Required: Command object } ``` **Example Request**: ```json theme={null} { "dataSource": "main", "database": "mydb", "command": { "dbStats": 1, "scale": 1024 } } ``` **Response**: ```json theme={null} { "result": { "db": "mydb", "collections": 5, "views": 0, "objects": 1523, "avgObjSize": 512, "dataSize": 780288, "storageSize": 1024000, "ok": 1 } } ``` ## Quick cURL Examples ```bash theme={null} # Insert a document curl -X POST http://localhost:3000/data/v1/action/insertOne \ -H "Content-Type: application/json" \ -H "apiKey: your-api-key" \ -d '{"dataSource": "main", "database": "mydb", "collection": "users", "document": {"name": "John Doe"}}' # Find documents curl -X POST http://localhost:3000/data/v1/action/find \ -H "Content-Type: application/json" \ -H "apiKey: your-api-key" \ -d '{"dataSource": "main", "database": "mydb", "collection": "users", "filter": {"name": "John Doe"}}' # Update a document curl -X POST http://localhost:3000/data/v1/action/updateOne \ -H "Content-Type: application/json" \ -H "apiKey: your-api-key" \ -d '{"dataSource": "main", "database": "mydb", "collection": "users", "filter": {"name": "John Doe"}, "update": {"$set": {"active": true}}}' # Count documents curl -X POST http://localhost:3000/data/v1/action/countDocuments \ -H "Content-Type: application/json" \ -H "apiKey: your-api-key" \ -d '{"dataSource": "main", "database": "mydb", "collection": "users", "filter": {"status": "active"}}' # Aggregate data curl -X POST http://localhost:3000/data/v1/action/aggregate \ -H "Content-Type: application/json" \ -H "apiKey: your-api-key" \ -d '{"dataSource": "main", "database": "mydb", "collection": "orders", "pipeline": [{"$match": {"status": "completed"}}, {"$group": {"_id": "$customerId", "total": {"$sum": "$amount"}}}]}' ``` ## Security Considerations * **API Key Authentication**: All endpoints require a valid API key * **Input Validation**: Requests are validated before processing * **Error Handling**: Proper error responses without exposing sensitive information * **Rate Limiting**: Consider implementing rate limiting for production use ## Use Cases The Data API is ideal for: * **Admin Dashboards**: Building administrative interfaces for data management * **Data Integration**: Connecting external systems to your MongoDB database * **Rapid Prototyping**: Quickly testing database operations and queries * **Analytics Tools**: Building custom analytics and reporting tools * **Mobile Apps**: Providing backend API for mobile applications ## Complete Example Want to see the full working code? Check it out on GitHub: > [card] [Complete Data API Example](https://github.com/modelence/examples/tree/main/data-api) > > See the complete source code for this example on GitHub, including all endpoints and configuration. ## Next Steps * Explore the [Store API Reference](/api-reference/modelence/server/classes/Store) for advanced MongoDB operations * Learn about [Authentication](/authentication) for more secure authentication methods * Check out the [Modules Guide](/core-concepts/modules) to understand how to organize your application # Deploy Setup Source: https://docs.modelence.com/deploy/setup Set up an existing Node.js project for Modelence Cloud by writing modelence.config.json This page is written for a coding agent. It describes what Modelence Cloud runs, the `modelence.config.json` file that tells it how, and the steps to set up an existing Node.js project. If you are a person, hand it to your agent: ```text theme={null} Use https://docs.modelence.com/deploy/setup.md to set up Modelence deployment for this project ``` ## What Modelence Cloud runs * **A Docker image built from the repository** on an official Node.js image, 18 or newer (default `node-22-slim`, set with `image`). The `build` commands run in order in the resource's root; only npm is preinstalled. * **One web process**, started with the resource's `start` commands. The last one must keep running and listen on the port in the `PORT` environment variable — a hardcoded port never receives traffic. * **Optional static directories** (the resource's `static`) served in front of that process by the platform. Requests that match no file fall back to the directory's `index.html`, so single-page apps route on the client. * **Optional managed PostgreSQL databases and Redis caches**, declared in `resources` next to the service. A deploy creates each one in the environment's region, and the app gets its connection details through the variables `env` ties to it. They need a paid Modelence Cloud plan. * **Optional telemetry**, a `resources` entry of type `"telemetry"`. It gives the environment a private OpenTelemetry endpoint for the app's traces and metrics, kept for 30 days and shown on the environment's **Monitoring** page. It needs a Modelence Cloud plan with monitoring (Pro and up). Logs need no setup: the app's output is collected and shown on the **Logs** page. * **Environment variables injected at start:** * `MONGODB_URI` and `MONGO_URL` — a MongoDB Atlas database provisioned for this environment (both hold the same connection string). * `SITE_URL` and `ROOT_URL` — the environment's public URL (both hold the same value). * `PORT` — the port the web process must listen on. * Any variables the user defines in the dashboard under **Environment variables**. * The variables `env` ties to a managed resource, such as `DATABASE_URL` from a PostgreSQL database's `url`, or `OTEL_EXPORTER_OTLP_ENDPOINT` from telemetry's `endpoint`. Names starting with `MODELENCE_`, and `PORT`, are reserved and cannot be defined by the user. ## modelence.config.json reference `modelence.config.json` sits at the project root and is the whole contract between the project and Modelence Cloud. Comments (`//`, `/* */`) and trailing commas are allowed. Apart from a resource's `type`, every key is optional; a missing key takes the default. The file has two top-level sections: `resources` (what the app is made of) and `env` (the variables it expects). | Key | Type | Default | Meaning | | - | - | - | - | | `$schema` | string | — | Set to `https://cloud.modelence.com/schema/modelence.config.json?version=1` for editor validation and completion. `version` is the format version the file is written for. | | `resources` | object | `{}` | Everything the app is made of, keyed by a name you choose (`"api"`, `"main-db"`): the service, and any managed databases, caches and telemetry. Exactly one service is supported today. | | `env` | object | `{}` | The variables the app expects, keyed by name. See below. | A service entry of `resources` takes: | Key | Type | Default | Meaning | | - | - | - | - | | `type` | `"service"` | required | What the resource is. `"service"` is a Node.js app built from this repository. | | `image` | string | `"node-22-slim"` | Base image, `node--`: a Node.js major (`"node-22-slim"`) or exact version (`"node-22.23.1-alpine"`), `18` or newer. `slim` is glibc and works with prebuilt native binaries; `alpine` is smaller. | | `root` | string | `"."` | Subdirectory that holds the app, relative to the repository root (monorepos). Commands run there, and `static` directories are relative to it. | | `build.commands` | string\[] | `["npm install"]` | Commands that install dependencies and build the app, run in order. `[]` means there is no build step. | | `start.commands` | string\[] | none | Commands that start the web process, run in order; the last one must keep running. Omit `start` when there is no process: the site is static only and `static` must be set. | | `dev.commands` | string\[] | the package.json `dev` script in `root` | Commands `modelence dev` runs locally in `root`, in order, with the connected environment's variables; the last one must keep running. Never used by a deploy. | | `static` | `[{ path, dir }]` | `[]` | Directories to serve. `path` is an absolute URL prefix (`"/"`, `"/docs"`); `dir` is relative to `root` and must exist after the build. | A managed resource entry of `resources` takes: | Key | Type | Default | Meaning | | - | - | - | - | | `type` | `"postgres"` \| `"redis"` \| `"telemetry"` | required | `"postgres"` is a PostgreSQL database, `"redis"` a Redis cache, `"telemetry"` the environment's OpenTelemetry endpoint. | | `plan` | string | the smallest | The size to create it with. PostgreSQL: `postgres-1gb`, `postgres-2gb`, `postgres-4gb`, `postgres-8gb`, `postgres-16gb` (the RAM of the database). Redis: `redis-250mb`, `redis-1gb`, `redis-5gb` (the data it holds). Telemetry takes no `plan`. | A deploy creates every managed resource the file declares that the environment doesn't have yet, and the new version starts only once they are ready. Resources are matched by name, so the same file works in every environment: * A resource that already exists is kept as it is, with its data. `plan` is read only when the resource is created, so changing it later has no effect. * A resource removed from the file is not deleted. Delete it in the dashboard under **Resources** when it is no longer needed; a database or cache is billed until then. * Renaming a resource creates a new, empty one. The old one stays until it is deleted. An environment can have up to 10 managed resources, telemetry included, and at most one of them can be telemetry. Each entry of `env` declares one variable: | Key | Type | Default | Meaning | | - | - | - | - | | `type` | `"text"` \| `"secret"` \| `"resource"` | `"text"` | `"secret"` is hidden in the dashboard variable list and revealed one value at a time, with each view logged. `"resource"` takes the value from a managed resource; see below. | | `scopes` | (`"build"` \| `"runtime"`)\[] | `["runtime"]` | Which phases the variable reaches. `"runtime"` is the running app; `"build"` is the build commands — needed for anything a bundler inlines, such as Vite's `VITE_*`. A value scoped to `["build"]` alone never reaches the running app. | | `value` | string | — | A non-secret literal committed with the repository (a base path, a public API URL). Omit it to declare only the name: the dashboard then lists the variable and the user sets it per environment. A `"secret"` may never carry a value. | | `required` | boolean | `true` | Whether the app needs a value to run. A deploy asks for every required variable that has no value, and a CI deploy fails without one. Set `false` for a variable the app runs without (an optional integration's key). | A value set in the dashboard overrides a `value` written here, so a literal in the file is the committed default rather than a fixed constant. A variable with `"type": "resource"` takes its value from one output of a managed resource in the same file, and takes only these keys: | Key | Type | Meaning | | - | - | - | | `type` | `"resource"` | Required. | | `resource` | string | The name of a `postgres`, `redis` or `telemetry` entry in `resources`. | | `output` | string | Which value of the resource. PostgreSQL: `url`, `host`, `port`, `user`, `password`, `database`. Redis: `url`, `host`, `port`, `password`. Telemetry: `endpoint`, `headers`. | The `url` output is a full connection string: `postgresql://...?sslmode=require` for PostgreSQL and `rediss://...` (TLS) for Redis. The other outputs are its parts, for clients that read them separately, such as `PGHOST` and `PGPASSWORD`. These variables reach the running app only, not the build commands. They can't be set or changed in the dashboard, where they are listed with the resource they come from. Telemetry's outputs are the values of the standard OpenTelemetry variables: `endpoint` for `OTEL_EXPORTER_OTLP_ENDPOINT` and `headers` for `OTEL_EXPORTER_OTLP_HEADERS`, which holds the environment's credentials. The endpoint takes OTLP over HTTP and is private: only the running app reaches it, not the build or a local machine. > [!NOTE] > > Apps built on the Modelence framework need no file: `npx modelence@latest deploy` recognizes the > `modelence` dependency and keeps building them locally, as it always has. To build one on Modelence Cloud > instead, describe it like any other Node.js app: `"build": { "commands": ["npm ci", "npm run build"] }` > and `"start": { "commands": ["npm start"] }`. **Missing, empty and none**: a missing `build` runs `npm install`; `"build": { "commands": [] }` means there is no build step. A missing `start` means there is no process. An empty command string `""` is invalid and is rejected. ## Examples **Express API only** — no build step, the server serves everything: ```json modelence.config.json theme={null} { "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1", "resources": { "api": { "type": "service", "image": "node-22-slim", "build": { "commands": ["npm ci"] }, "start": { "commands": ["node server.js"] } } } } ``` **Vite static site** — built once, served by the platform, no process: ```json modelence.config.json theme={null} { "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1", "resources": { "web": { "type": "service", "image": "node-22-slim", "build": { "commands": ["npm ci", "npm run build"] }, "static": [{ "path": "/", "dir": "dist" }] } } } ``` **Express API + Vite frontend** — the frontend in `client/` is built into `client/dist` and served at `/`; requests that match no file reach the API. `VITE_API_URL` is scoped to the build as well because Vite inlines it while building: ```json modelence.config.json theme={null} { "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1", "resources": { "api": { "type": "service", "image": "node-22-slim", "build": { "commands": ["npm ci", "npm ci --prefix client", "npm run build --prefix client"] }, "start": { "commands": ["node server.js"] }, "static": [{ "path": "/", "dir": "client/dist" }] } }, "env": { "VITE_API_URL": { "value": "/api", "scopes": ["build", "runtime"] }, "STRIPE_SECRET_KEY": { "type": "secret" } } } ``` **Express API with PostgreSQL and Redis** - the deploy creates the database and the cache, and the app reads them from `DATABASE_URL` and `REDIS_URL`: ```json modelence.config.json theme={null} { "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1", "resources": { "api": { "type": "service", "image": "node-22-slim", "build": { "commands": ["npm ci"] }, "start": { "commands": ["node server.js"] } }, "main-db": { "type": "postgres", "plan": "postgres-1gb" }, "cache": { "type": "redis" } }, "env": { "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" }, "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" } } } ``` **Express API with telemetry** - the OpenTelemetry SDK reads the two variables, so requests and database calls reach the environment without code changes. Logs are already collected from the app's output, so `OTEL_LOGS_EXPORTER` turns off the SDK's own log export. The project depends on `@opentelemetry/auto-instrumentations-node`, which `--require` loads before the server: ```json modelence.config.json theme={null} { "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1", "resources": { "api": { "type": "service", "image": "node-22-slim", "build": { "commands": ["npm ci"] }, "start": { "commands": ["node --require @opentelemetry/auto-instrumentations-node/register server.js"] } }, "otel": { "type": "telemetry" } }, "env": { "OTEL_EXPORTER_OTLP_ENDPOINT": { "type": "resource", "resource": "otel", "output": "endpoint" }, "OTEL_EXPORTER_OTLP_HEADERS": { "type": "resource", "resource": "otel", "output": "headers" }, "OTEL_SERVICE_NAME": { "value": "api" }, "OTEL_LOGS_EXPORTER": { "value": "none" } } } ``` ## Setting up a project Follow these steps in order. Do not skip the verification step. 1. **Inspect `package.json`.** Read `scripts`, `engines.node`, `type` and the dependencies. Note which framework builds the frontend (Vite, Next.js, Create React App, Angular, Astro…) and what runs the server (Express, Fastify, Koa, Hono, NestJS, a framework's own server…). 2. **Pick the install command from the lockfile.** * `package-lock.json` in sync with `package.json` → `npm ci`. If it is stale or missing, use `npm install`. * `pnpm-lock.yaml` → `corepack enable && pnpm install --frozen-lockfile`. * `yarn.lock` → `corepack enable && yarn install --frozen-lockfile` (Yarn 1) or `corepack enable && yarn install --immutable` (Yarn 2+). Only npm is preinstalled in the build image; `corepack enable` makes pnpm and Yarn available at the version `packageManager` in `package.json` names. 3. **Find the build output.** Vite writes `dist/`, Create React App and Angular write `build/` or `dist//browser`, Astro writes `dist/`, Next.js needs `next build` and its own server (`next start`), not a static mount, unless `output: 'export'` is set. Check the framework config for a changed `outDir`. 4. **Check the start script.** `vite`, `vite preview`, `react-scripts start`, `next dev`, `nodemon`, `ts-node-dev` and `tsx watch` are development servers. Do not use them. Replace them with a production start (`node dist/server.js` after a TypeScript build, `next start`, `node server.js`) or, for a pure frontend, a static mount and no `start`. Do not add database migrations to `start.commands`: every container runs them on every start, several at once during a rollout, and a slow one is killed by the health check partway through. Leave migrations out of the file and tell the user to run them against the environment's database before deploying. A step may go first in `start.commands` only if it is fast and safe to run in parallel, such as `prisma generate`. 5. **Make the server read `PORT`.** The listen call must use `process.env.PORT`, for example `app.listen(Number(process.env.PORT) || 3000)`. Bind to all interfaces (the default), not to `127.0.0.1` only. If the frontend and the API are served together, the server must be the one process — the static mount handles the frontend files, the server handles everything else. 6. **Use the provided databases.** If the project needs MongoDB, read the connection string from `process.env.MONGODB_URI` (or `MONGO_URL`) instead of a hardcoded one. If it needs PostgreSQL or Redis that it doesn't already have hosted somewhere, declare a managed resource for it in step 7 and tie the variable the code reads (`DATABASE_URL`, `REDIS_URL`) to its `url` output. A database hosted elsewhere (Supabase, Neon, PlanetScale and so on) works as it is: keep the connection code and read its URL and keys from environment variables. Other databases, such as MySQL, are not provisioned. See [Compatibility](#when-the-project-is-not-compatible). 7. **Write `modelence.config.json`** at the repository root with the values found above, as a single service entry in `resources` (`"type": "service"`). Pick `image` from `engines.node` (default `node-22-slim`; use `slim` unless the project already builds on Alpine). Set `root` when the app lives in a subdirectory. Add any managed resources from step 6 next to the service, with their variables in `env`. Add a `telemetry` resource only when the user asks for traces or metrics, or the project already uses OpenTelemetry: a deploy fails on a plan without monitoring. Tie `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_HEADERS` to its outputs instead of a hardcoded collector. Add `"$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1"`. 8. **Verify locally.** Run the build commands, then the start commands with `PORT=3000` set, in order — exactly as written in the file — and confirm the app answers on `http://localhost:3000` (for a static site, confirm the `dir` exists after the build and holds `index.html`). Fix the file or the code until this works; a deploy runs the same commands. 9. **Commit `modelence.config.json`** together with any code changes (the `PORT` change, the production start script). 10. **Run `npx modelence@latest deploy`** in the project directory yourself, with a timeout of at least 15 minutes. It opens the browser, where the user signs in, picks the organization, application and environment (or creates a new application or environment there) and enters the values of any required variables the environment does not have yet. Tell the user to confirm there, then wait for the command to finish: it uploads the project and follows the build until the app is live. If you know the target, pass `--app --env ` to preselect it; the user still confirms it in the browser. ### Runtime values and secrets When the app needs a value that must not be committed — an API key, an OAuth secret, a third-party URL — declare it by name in the file's `env` section, without a `value` and with `"type": "secret"` for anything sensitive. The deploy asks the user for it in the browser; it can be changed later in the Modelence Cloud dashboard under **Environment variables**. A value only the build needs (a `VITE_*` or `NEXT_PUBLIC_*` variable that is inlined into the frontend) gets `"scopes": ["build", "runtime"]`; never give a build scope to anything the browser must not see. Mark a variable the app runs without `"required": false`. Read the values from `process.env` as usual. Non-secret settings that belong with the code (a base path, a public API path) go in the file's `env` section instead, with a `value`, so they are versioned with the repository. Give anything a bundler inlines `"scopes": ["build", "runtime"]` so it reaches the build as well as the running app. ## When the project is not compatible Report the project as not compatible with Modelence Cloud, and say why, when: * **It is not a Node.js application** — Java, Python, Go, PHP, Ruby, .NET and so on, even with a Node.js frontend in front. The image runs Node.js only. * **It requires a second long-running process**: a separate worker or queue consumer, a scheduler process, or a database other than the provided ones (MySQL, Elasticsearch…) that would have to run alongside the app. One web process is run, and MongoDB, PostgreSQL and Redis are the only databases provisioned. * **It needs Docker Compose** or a custom Dockerfile to run. A database hosted elsewhere is not a reason to report the project as not compatible. An app that connects over the network to Supabase, Neon, PlanetScale, a managed Redis or any other hosted database deploys as usual: keep its connection code, and tell the user to add the URL and keys in the dashboard under **Environment variables**, marked as secret. A key the frontend bundler inlines, such as `VITE_SUPABASE_URL`, also needs to be available at build time, as described in [Runtime values and secrets](#runtime-values-and-secrets). Then suggest what the user can do instead: replace the database with one that is provided (MongoDB through `MONGODB_URI`, or a managed PostgreSQL or Redis resource), or keep the incompatible parts on another host and deploy only the Node.js web app. Do not move a worker, queue consumer or scheduled job into the web process. The web process can run as several replicas, and each one would run every job — emails sent twice, charges made twice. If the user wants to do it anyway, tell them that each job needs a lock held in the database, so that only one replica runs it at a time. ## Meteor > [!NOTE] > > Early support — the commands below work but Meteor is not yet a first-class runtime. Meteor bundles its own server; build it into a directory outside the source tree and start the bundle with Node.js. `ROOT_URL` and `MONGO_URL`, which Meteor reads at start, are already injected. Match `image` to the Meteor release: Meteor 3 runs on Node 22. ```json modelence.config.json theme={null} { "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1", "resources": { "app": { "type": "service", "image": "node-22-slim", "build": { "commands": [ "curl https://install.meteor.com/ | sh", "meteor npm install", "meteor build --directory /tmp/meteor-build --server-only", "cd /tmp/meteor-build/bundle/programs/server && npm install" ] }, "start": { "commands": ["node /tmp/meteor-build/bundle/main.js"] } } } } ``` # Built-in Email Source: https://docs.modelence.com/email/index Send transactional emails out of the box with no provider setup Modelence sends transactional emails — verification, password reset, and any custom emails you trigger via `sendEmail` — through a built-in managed email provider. No provider setup, no API keys, no SMTP credentials. Apps connected to Modelence Cloud get email working immediately. If you outgrow the managed provider or need custom domains, attachments, or full deliverability control, you can swap in a [custom provider](/email/providers) (Resend, Amazon SES, or SMTP) at any time. ## Built-in Managed Email (Default) > [!NOTE] > > Built-in managed email requires **`modelence` v0.18.0 or newer**. Earlier versions still require you to configure a provider explicitly. Update with `npm install modelence@latest`. When your app is connected to Modelence Cloud, the managed email provider is enabled automatically. You don't need to install any package, configure credentials, or pass a `provider` to `startApp`. ### Minimum setup ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ // ... your other app configuration email: { verification: { subject: 'Verify your email', redirectUrl: 'https://yourdomain.com/email-verified', }, passwordReset: { subject: 'Reset your password', redirectUrl: 'https://yourdomain.com/password-reset-success', }, }, }); ``` That's it. Verification and password reset emails go out automatically. You can also call `sendEmail` for custom transactional messages (see [Sending Custom Emails](#sending-custom-emails)). ### How it works * Outbound mail is relayed through Modelence Cloud (`/api/email/send`), which sends via Resend on a Modelence-owned domain. * You can still pass `from: '"Your App" '` to set a friendly **name**; the address part is replaced by the managed sender. The `replyTo` field works normally so users can still reply to your support inbox. * Local development (no Modelence Cloud connection) falls back to the legacy "no provider configured" behavior so misconfigurations fail loudly during development. ### Limitations in v1 The managed provider focuses on the common transactional case. It does **not** support: * `cc` / `bcc` recipients * File attachments * Custom email headers * Custom sender domains If you call `sendEmail` with any of these, Modelence throws a clear error. Use a [custom provider](/email/providers) when you need them. ## Custom Email Templates You can customize the HTML for verification and password reset emails. Templates work the same whether you use the built-in provider or a custom one: ```typescript theme={null} startApp({ // ... your other app configuration email: { verification: { subject: 'Welcome! Please verify your email', template: ({ name, email, verificationUrl }) => `

Welcome ${name}!

Please click the link below to verify your email address:

Verify Email `, redirectUrl: 'https://yourdomain.com/email-verified', }, passwordReset: { subject: 'Reset Your Password', template: ({ name, email, resetUrl }) => `

Hello ${name}

Click the link below to reset your password:

Reset Password

If you didn't request this, please ignore this email.

`, redirectUrl: 'https://yourdomain.com/password-reset-success', }, }, }); ``` ## Sending Custom Emails Use `sendEmail` to send arbitrary transactional emails — order confirmations, invites, notifications, anything you trigger from your own code. It routes through whichever provider is active (managed or custom), so the call site stays the same. ### Basic example ```typescript theme={null} import { sendEmail } from 'modelence/server'; await sendEmail({ to: 'user@example.com', subject: 'Welcome to Acme', html: '

Welcome!

Thanks for signing up.

', }); ``` ### Calling `sendEmail` from a mutation A typical use case — sending a notification when a user completes an action: ```typescript theme={null} import { Module, sendEmail } from 'modelence/server'; import { z } from 'zod'; export default new Module('orders', { mutations: { async create(args, { user }) { const { items } = z.object({ items: z.array(z.string()) }).parse(args); const order = await dbOrders.insertOne({ userId: user.id, items, createdAt: new Date(), }); await sendEmail({ to: user.emails[0].address, subject: `Order #${order.insertedId} confirmed`, html: `

Thanks for your order!

We received your order with ${items.length} item(s).

`, }); return { orderId: order.insertedId }; }, }, }); ``` ### Plain-text and multipart emails Provide `text` for clients that don't render HTML, or both `html` and `text` for a multipart message: ```typescript theme={null} await sendEmail({ to: 'user@example.com', subject: 'Your weekly digest', text: 'You have 3 new notifications. Visit https://yourdomain.com to view.', html: '

You have 3 new notifications.

', }); ``` ### Sending to multiple recipients ```typescript theme={null} await sendEmail({ to: ['alice@example.com', 'bob@example.com'], replyTo: 'support@yourdomain.com', subject: 'Team update', html: '

Here is this week\'s update.

', }); ``` ### Email Payload Options ```typescript theme={null} { from?: string; // Sender address (managed provider uses the name only) to: string | string[]; // Recipient(s) subject: string; // Email subject html?: string; // HTML content text?: string; // Plain text content cc?: string | string[]; // CC recipients (custom provider only) bcc?: string | string[]; // BCC recipients (custom provider only) replyTo?: string | string[]; // Reply-to address(es) headers?: Record; // Custom headers (custom provider only) attachments?: EmailAttachment[]; // File attachments (custom provider only) } ``` You must provide either `html` or `text` (or both). Fields marked **custom provider only** are rejected by the built-in managed provider — see [Custom Email Providers](/email/providers) if you need them. ## Troubleshooting ### Error: "Modelence managed email does not support cc, bcc, attachments, or custom headers" The built-in managed provider does not support these fields in v1. Either remove them from your `sendEmail` call, or configure a [custom provider](/email/providers) (Resend, SES, or SMTP). ### Error: "Email provider is not configured" You're running locally without a Modelence Cloud connection and haven't set a `provider`. Either: * Connect your app to Modelence Cloud to use the managed provider, or * Configure a [custom provider](/email/providers). ## Next Steps * Use a [custom email provider](/email/providers) for attachments, custom domains, or specific vendor requirements * Learn about [Authentication](/authentication) to understand how email verification works * Explore [User Management](/authentication/user-management) features * Review the [API Reference](/api-reference) for more details on email functions # Custom Email Providers Source: https://docs.modelence.com/email/providers Use Resend, Amazon SES, or SMTP instead of the built-in managed email provider By default, Modelence sends transactional email through its [built-in managed provider](/email) — no setup required. Configure a custom provider only when you need: * A custom sender domain / full DKIM control * Attachments, `cc` / `bcc`, or custom email headers * A specific deliverability vendor (Resend, SES in your own AWS account, your own SMTP relay) Setting `email.provider` on `startApp` overrides the managed provider. If you omit `provider`, Modelence keeps using the managed email service. ## Supported Providers * **[Resend](/api-reference/@modelence/resend/index)** — modern email API service * **[Amazon SES](/api-reference/@modelence/aws-ses/index)** — AWS Simple Email Service * **[SMTP](/api-reference/@modelence/smtp/index)** — any SMTP-compatible email service ## 1. Install a provider package ```bash theme={null} # For Resend npm install @modelence/resend # For Amazon SES npm install @modelence/aws-ses # For SMTP npm install @modelence/smtp ``` ## 2. Configure credentials ### Option A: Cloud Configuration (Recommended) 1. Go to [cloud.modelence.com](https://cloud.modelence.com) 2. Choose your environment 3. Open the **Application** tab 4. Select the **Email** configuration section 5. Choose your provider and enter the required credentials: **For Resend:** * API Key (get it from [resend.com/api-keys](https://resend.com/api-keys)) **For Amazon SES:** * Region (e.g., `us-east-1`) * Access Key ID * Secret Access Key See [AWS SES documentation](https://docs.aws.amazon.com/ses/) for obtaining credentials. **For SMTP:** * Host (e.g., `smtp.gmail.com`) * Port (usually `465` for secure connections) * Username * Password The cloud configuration syncs to your app automatically. ### Option B: Local Environment Variables Useful for local development: **For Resend:** ```bash theme={null} MODELENCE_EMAIL_RESEND_API_KEY=your_resend_api_key ``` **For Amazon SES:** ```bash theme={null} MODELENCE_EMAIL_AWS_SES_REGION=us-east-1 MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID=your_access_key_id MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY=your_secret_access_key ``` **For SMTP:** ```bash theme={null} MODELENCE_EMAIL_SMTP_HOST=smtp.example.com MODELENCE_EMAIL_SMTP_PORT=465 MODELENCE_EMAIL_SMTP_USER=your_smtp_username MODELENCE_EMAIL_SMTP_PASS=your_smtp_password ``` Cloud configuration takes precedence over local environment variables. ## 3. Pass the provider to `startApp` ```typescript theme={null} import { startApp } from 'modelence/server'; import resendProvider from '@modelence/resend'; // or import awsSesProvider from '@modelence/aws-ses'; // or import smtpProvider from '@modelence/smtp'; startApp({ // ... your other app configuration email: { provider: resendProvider, from: 'noreply@yourdomain.com', verification: { subject: 'Verify your email', redirectUrl: 'https://yourdomain.com/email-verified', }, passwordReset: { subject: 'Reset your password', redirectUrl: 'https://yourdomain.com/password-reset-success', }, }, }); ``` With a custom provider, the full [email payload](/email#email-payload-options) is supported — including `cc`, `bcc`, custom headers, and attachments: ```typescript theme={null} await sendEmail({ from: 'noreply@yourdomain.com', to: 'user@example.com', subject: 'Invoice', html: '

Your Invoice

', attachments: [ { filename: 'invoice.pdf', content: pdfBuffer, contentType: 'application/pdf', }, ], }); ``` ## Troubleshooting ### SMTP connection issues * Verify your SMTP credentials are correct * Check that the port is correct (usually 465 for secure connections) * Ensure your firewall allows outbound connections on the SMTP port * Some email providers require you to enable "less secure app access" or create an app-specific password ### AWS SES sending limits If you're in the AWS SES sandbox: * You can only send emails to verified email addresses * Request production access to send to any email address * Verify your sending domain or individual email addresses in the AWS Console ### Error: "Email provider is not configured" You're running locally without a Modelence Cloud connection and haven't set `email.provider`. Either: * Connect your app to Modelence Cloud to use the [built-in managed provider](/email), or * Configure a provider via `startApp({ email: { provider, ... } })`. # Files Source: https://docs.modelence.com/files Upload and manage files with Modelence Cloud storage Modelence provides built-in file storage through Modelence Cloud. Files are organized by visibility — either `public` (accessible via a permanent URL) or `private` (accessible only via a time-limited signed URL). > [!WARNING] > > **File operations are server-only.** `getUploadUrl`, `getFileUrl`, `downloadFile`, and `deleteFile` are imported from `modelence/server` and can only be called from your server-side code (queries, mutations, cron jobs). They are **not** callable directly from the browser. > > This is deliberate. Each operation issues a signed URL or performs a delete against Modelence Cloud using your app's credentials, for whatever `filePath` it is given. The framework has no way to know which user owns which file, so exposing these to the client would let any caller act on any path. **You** decide who can touch which file by wrapping these calls in your own queries/mutations and enforcing ownership there — see [Exposing file operations to the client](#exposing-file-operations-to-the-client). ## Uploading a File `getUploadUrl` returns a presigned URL and form fields. POST these together as `FormData` to upload the file directly to storage: ```ts theme={null} import { getUploadUrl } from 'modelence/server'; import fs from 'fs/promises'; const { url, fields, filePath } = await getUploadUrl({ filePath: 'photo.png', contentType: 'image/png', visibility: 'public', }); const data = await fs.readFile('./photo.png'); const formData = new FormData(); for (const [key, value] of Object.entries(fields)) { formData.append(key, value); } formData.append('file', new Blob([data], { type: 'image/png' })); await fetch(url, { method: 'POST', body: formData }); console.log(filePath); // e.g. 'public/photo.png' ``` The `visibility` field controls access: * `"public"` — the file is accessible via a permanent URL * `"private"` — the file requires a signed URL to access ## Getting a File URL Returns a URL for displaying or linking to a file. For public files this is a permanent URL; for private files it is a time-limited presigned URL. ```ts theme={null} import { getFileUrl } from 'modelence/server'; const { url } = await getFileUrl('public/photo.png'); console.log(url); // Permanent public URL const { url: privateUrl } = await getFileUrl('private/report.pdf'); console.log(privateUrl); // Time-limited presigned URL ``` ## Downloading a File Returns a presigned download URL for a private file. ```ts theme={null} import { downloadFile } from 'modelence/server'; const { downloadUrl } = await downloadFile('private/report.pdf'); // Redirect the user to downloadUrl or fetch it server-side ``` ## Deleting a File ```ts theme={null} import { deleteFile } from 'modelence/server'; await deleteFile('public/photo.png'); await deleteFile('private/report.pdf'); ``` ## File Paths File paths always include the visibility prefix: `public/` or `private/`. The upload functions return the full `filePath` (including prefix) in their result, which you can store and pass to the other functions. ```ts theme={null} import { getUploadUrl } from 'modelence/server'; const { filePath } = await getUploadUrl({ filePath: 'avatars/user-123.png', contentType: 'image/png', visibility: 'private', }); // filePath === 'private/avatars/user-123.png' const { url } = await getFileUrl(filePath); ``` ## Exposing file operations to the client Because the file functions are server-only, the browser reaches them through **your own** queries and mutations. This is where you enforce authorization: never accept a raw client-supplied `filePath` and forward it blindly — derive the path from your own data and verify the current user is allowed to act on it. The pattern below stores file ownership in a Store and checks it on every operation. Uploading returns the presigned URL to the client, which performs the actual upload directly to storage. ```ts theme={null} import { Module, Store, schema, getUploadUrl, getFileUrl, deleteFile } from 'modelence/server'; import { ObjectId } from 'mongodb'; const dbDocuments = new Store('documents', { schema: { userId: schema.userId(), filePath: schema.string(), createdAt: schema.date(), }, }); export default new Module('documents', { stores: [dbDocuments], queries: { // Hand out a time-limited URL only for a document the caller owns. async getUrl({ documentId }, { user }) { if (!user) { throw new Error('Authentication required'); } const doc = await dbDocuments.requireOne({ _id: new ObjectId(documentId as string), userId: new ObjectId(user.id), }); return getFileUrl(doc.filePath); }, }, mutations: { // Issue an upload URL for a path scoped to the caller, then record ownership. async requestUpload({ contentType }, { user }) { if (!user) { throw new Error('Authentication required'); } const filePath = `private/users/${user.id}/${new ObjectId().toString()}`; const upload = await getUploadUrl({ filePath, contentType: contentType as string, visibility: 'private', }); await dbDocuments.insertOne({ userId: new ObjectId(user.id), filePath, createdAt: new Date(), }); return upload; // { url, fields, filePath } — the client POSTs the file to `url` }, // Only the owner can delete. async remove({ documentId }, { user }) { if (!user) { throw new Error('Authentication required'); } const doc = await dbDocuments.requireOne({ _id: new ObjectId(documentId as string), userId: new ObjectId(user.id), }); await deleteFile(doc.filePath); await dbDocuments.deleteOne({ _id: doc._id }); }, }, }); ``` The client then calls your guarded methods — e.g. `callMethod('documents.requestUpload', { contentType })` — instead of the file functions directly. Public assets that are safe for anyone to read can be served straight from their permanent `public/...` URL without a query. # Introduction Source: https://docs.modelence.com/index Modelence is a production cloud for your backend, databases and scheduled jobs. It deploys your app and keeps operating it after that: crashed processes are restarted, traffic is rerouted when an instance fails and capacity is added under load, and you get a report of what happened. Apps run on AWS in the region you choose, with managed MongoDB, PostgreSQL and Redis databases next to them. Logs, metrics and job runs are collected from the first deploy, and production databases are [backed up](/cloud/backups) automatically. ## Get started The quickest way to deploy is to hand it to your coding agent. Paste this into Claude Code, Cursor or Codex in your project: ```text theme={null} Deploy using https://modelence.com/skill.md ``` The agent reads your project, writes `modelence.config.json` to describe what it needs, and deploys it. You can also sign up at [cloud.modelence.com](https://cloud.modelence.com) and connect your repository from the dashboard. > [card] [Deploy Setup](/deploy/setup) > > What Modelence Cloud runs and how `modelence.config.json` describes your app > [card] [Backups](/cloud/backups) > > How production databases are backed up, restored and exported > [card] [Local Setup](/setup) > > Connect a project running on your machine to a Modelence environment # Indexes Source: https://docs.modelence.com/indexes Configure MongoDB and Atlas Search indexes for your stores Modelence lets you configure indexes directly on each `Store`. Use: * `indexes` for regular MongoDB indexes (performance and constraints) * `searchIndexes` for MongoDB Atlas Search * `indexCreationMode` to control startup behavior ## MongoDB Indexes Configure indexes to improve query performance: ```typescript theme={null} export const dbPosts = new Store('posts', { schema: { title: schema.string(), authorId: schema.userId(), publishedAt: schema.date(), status: schema.string(), }, indexes: [ // Single field index { key: { authorId: 1 } }, // Compound index { key: { status: 1, publishedAt: -1 } }, // Named index { key: { title: 'text' }, name: 'title_text_index' }, // Unique index { key: { slug: 1 }, unique: true } ] }); ``` Modelence automatically creates these indexes when the application starts. > [!NOTE] > > Starting from `modelence@0.12.0`, Modelence manages framework-created indexes > using this strategy. > > Modelence manages framework-created indexes with a `_modelence_` name prefix. > If you provide `name`, Modelence still prefixes it automatically. > During startup reconciliation, Modelence will create missing managed indexes, > drop outdated managed indexes, and recreate changed ones. Manual indexes that do not use the `_modelence_` prefix are preserved unless they conflict with code-defined index keys. ### Common Index Options `indexes` accepts MongoDB index options like `unique`, `sparse`, `expireAfterSeconds`, and `partialFilterExpression`: ```typescript theme={null} indexes: [ { key: { email: 1 }, unique: true }, { key: { deletedAt: 1 }, sparse: true }, { key: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL { key: { status: 1 }, partialFilterExpression: { status: { $exists: true } } }, ] ``` ## Index Creation Mode By default, store indexes are created in the background during startup.\ Set `indexCreationMode: 'blocking'` for indexes that must be created before startup continues. ```typescript theme={null} export const locksCollection = new Store('_modelenceLocks', { schema: { resource: schema.string(), instanceId: schema.string(), acquiredAt: schema.date(), }, indexes: [ { key: { resource: 1 }, unique: true }, { key: { resource: 1, acquiredAt: 1 } }, ], indexCreationMode: 'blocking', }); ``` Startup ordering: 1. `blocking` indexes are awaited before migrations begin. 2. Migrations are then started. 3. `background` indexes may continue running in parallel with migrations. In multi-instance deployments, index creation is coordinated through a distributed `indexes` lock so only one instance performs reconciliation at a time. If index creation fails for a store, startup continues and a warning is logged. > [!TIP] > > See [Migrations](/core-concepts/migrations) for startup and race-condition guidance with cron jobs. ## MongoDB Atlas Search Indexes For advanced full-text search capabilities using MongoDB Atlas Search, configure search indexes: ```typescript theme={null} export const dbArticles = new Store('articles', { schema: { title: schema.string(), content: schema.string(), tags: schema.array(schema.string()), category: schema.string(), authorId: schema.userId(), }, indexes: [ { key: { authorId: 1 } }, ], searchIndexes: [ { name: 'article_search', definition: { mappings: { dynamic: false, fields: { title: { type: 'string', analyzer: 'lucene.standard' }, content: { type: 'string', analyzer: 'lucene.standard' }, tags: { type: 'string', analyzer: 'lucene.keyword' }, category: { type: 'string', analyzer: 'lucene.keyword' } } } } } ] }); ``` ### Using Search Indexes Once configured, use the search indexes with MongoDB's aggregation pipeline: ```typescript theme={null} // Full-text search across title and content const results = await dbArticles.aggregate([ { $search: { index: 'article_search', text: { query: 'machine learning', path: ['title', 'content'] } } }, { $limit: 10 } ]).toArray(); // Search with filters const filteredResults = await dbArticles.aggregate([ { $search: { index: 'article_search', compound: { must: [ { text: { query: 'tutorial', path: 'title' } } ], filter: [ { text: { query: 'javascript', path: 'category' } } ] } } } ]).toArray(); ``` > [!NOTE] > > Search indexes require MongoDB Atlas. They are automatically created when your > application starts, similar to regular indexes. ## Vector Search Indexes For Atlas Vector Search, you can define a vector index in `searchIndexes`: ```typescript theme={null} export const dbDocuments = new Store('documents', { schema: { title: schema.string(), embedding: schema.array(schema.number()), }, indexes: [], searchIndexes: [ Store.vectorIndex({ field: 'embedding', dimensions: 1536, similarity: 'cosine', }), ], }); ``` See [Voyage AI Tutorial](/voyage-ai) for an end-to-end vector search example. # Live Queries Source: https://docs.modelence.com/live-queries Real-time data synchronization with automatic updates using LiveData and TanStack Query. Available since modelence@0.15.1 and @modelence/react-query@1.2.1. Live Queries in Modelence provide real-time data synchronization between your server and client. When underlying data changes, connected clients automatically receive updated data without manual polling or refetching. ## Version Requirements Live Queries are available with the following minimum package versions: * `modelence >= 0.15.1` (requires `Store.watch()`, introduced in `0.15.1`) * `@modelence/react-query >= 1.2.1` ## Overview The live query system consists of three parts: 1. **Server-side `LiveData`** - Defines how to fetch data and watch for changes 2. **`ModelenceQueryProvider`** (or `connectModelenceQueryClient`) - Connects Modelence's live query system to TanStack Query 3. **`modelenceLiveQuery`** - Creates live query options for `useQuery` ## Client Setup ### 1. Provide a connected QueryClient `modelenceLiveQuery` needs a TanStack Query `QueryClient` connected to Modelence's live-query layer. The simplest way is to let `renderApp` handle it: if you don't mount your own provider, `renderApp` automatically wraps your app in `ModelenceQueryProvider`, which creates a `QueryClient` and connects it for you. ```tsx theme={null} // src/client/index.tsx import { renderApp } from 'modelence/client'; import routes from './routes'; renderApp({ loadingElement:
Loading…
, routesElement: routes, }); // No provider wiring needed — renderApp injects ModelenceQueryProvider. ``` If you need your own `QueryClient` (for example, to configure defaults or share it with other libraries), connect it yourself with `connectModelenceQueryClient` and mount your own `QueryClientProvider`. `renderApp` detects the already-connected client and will not inject a second provider. ```tsx theme={null} // src/client/index.tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { connectModelenceQueryClient, renderApp } from 'modelence/client'; import routes from './routes'; const queryClient = new QueryClient(); connectModelenceQueryClient(queryClient); renderApp({ loadingElement:
Loading…
, routesElement: ( {routes} ), }); ``` > [!WARNING] > > If you mount your own `QueryClientProvider` but never call > `connectModelenceQueryClient(queryClient)`, `modelenceLiveQuery` throws: > `Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount or call connectModelenceQueryClient().` ### 2. Use modelenceLiveQuery in Components Use `modelenceLiveQuery` with TanStack Query's `useQuery` hook. It works just like `modelenceQuery`, but data updates automatically when the server detects changes: ```tsx theme={null} import { useQuery } from '@tanstack/react-query'; import { modelenceLiveQuery } from 'modelence/client'; function TodoList({ userId }: { userId: string }) { const { data: todos, isLoading } = useQuery( modelenceLiveQuery('todo.getAll', { userId }) ); if (isLoading) return
Loading...
; return (
    {todos?.map(todo => (
  • {todo.title}
  • ))}
); } ``` ## Server Setup ### Returning LiveData from Query Handlers Live query handlers **must** return a `LiveData` object, not plain data. `LiveData` tells Modelence how to fetch the data and how to watch for changes. ```typescript theme={null} import { Module, LiveData } from 'modelence/server'; import { dbTodos } from './db'; export default new Module('todo', { stores: [dbTodos], queries: { // Standard query - returns data directly getById: async ({ id }) => { return await dbTodos.findById(id); }, // Live query - returns LiveData getAll: async ({ userId }) => { return new LiveData({ fetch: async () => await dbTodos.fetch({ userId }), watch: ({ publish }) => { const changeStream = dbTodos.watch(); changeStream.on('change', () => publish()); return () => changeStream.close(); }, }); }, }, }); ``` > [!WARNING] > > If a live query handler returns plain data instead of a `LiveData` object, the server will throw: `Live query handler for 'X' must return a LiveData object with fetch and watch functions.` ### LiveData Configuration `LiveData` accepts two functions: | Property | Type | Description | | - | - | - | | `fetch` | `() => Promise \| T` | Fetches the current data. Called on initial subscription and whenever `publish()` is called. | | `watch` | `({ publish }) => (() => void) \| void` | Sets up real-time monitoring. Call `publish()` to trigger a re-fetch. Return a cleanup function to unsubscribe when the client disconnects. | ### Using MongoDB Change Streams The most common pattern for the `watch` function is MongoDB change streams, which notify you when documents in a collection are inserted, updated, or deleted: ```typescript theme={null} import { LiveData } from 'modelence/server'; import { dbTodos } from './db'; // Watch all changes to a collection queries: { getAll: async ({ userId }) => { return new LiveData({ fetch: async () => await dbTodos.fetch({ userId }), watch: ({ publish }) => { const changeStream = dbTodos.watch(); changeStream.on('change', () => publish()); return () => changeStream.close(); }, }); }, } ``` You can also use a [pipeline](https://www.mongodb.com/docs/manual/changeStreams/#modify-change-stream-output) to filter which changes trigger updates: ```typescript theme={null} // Only watch for changes to a specific user's todos queries: { getAll: async ({ userId }) => { return new LiveData({ fetch: async () => await dbTodos.fetch({ userId }), watch: ({ publish }) => { const pipeline = [ { $match: { 'fullDocument.userId': userId } }, ]; const changeStream = dbTodos.watch(pipeline); changeStream.on('change', () => publish()); return () => changeStream.close(); }, }); }, } ``` > [!NOTE] > > MongoDB change streams require a **replica set** or **sharded cluster**. If you're using MongoDB Atlas, this is enabled by default. For local development, you need to configure a replica set. ## Complete Example Here's a full example of a live todo list: ### Server ```typescript theme={null} // src/server/db.ts import { Store, schema } from 'modelence/server'; export const dbTodos = new Store('todos', { schema: { title: schema.string(), isCompleted: schema.boolean(), userId: schema.userId(), createdAt: schema.date(), }, indexes: [ { key: { userId: 1 } }, ], }); ``` ```typescript theme={null} // src/server/module.ts import { Module, LiveData } from 'modelence/server'; import { z } from 'zod'; import { dbTodos } from './db'; export default new Module('todo', { stores: [dbTodos], queries: { getAll: async ({ userId }) => { return new LiveData({ fetch: async () => await dbTodos.fetch( { userId }, { sort: { createdAt: -1 } } ), watch: ({ publish }) => { const changeStream = dbTodos.watch(); changeStream.on('change', () => publish()); return () => changeStream.close(); }, }); }, }, mutations: { create: async (args, { user }) => { const { title } = z.object({ title: z.string() }).parse(args); await dbTodos.insertOne({ title, isCompleted: false, userId: user.id, createdAt: new Date(), }); }, toggleComplete: async (args) => { const { id, isCompleted } = z.object({ id: z.string(), isCompleted: z.boolean(), }).parse(args); await dbTodos.updateOne(id, { $set: { isCompleted } }); }, }, }); ``` ### Client ```tsx theme={null} // src/client/index.tsx import { renderApp } from 'modelence/client'; import TodoList from './pages/TodoList'; // renderApp injects ModelenceQueryProvider automatically — no manual wiring. renderApp({ loadingElement:
Loading…
, routesElement: , }); ``` ```tsx theme={null} // src/client/pages/TodoList.tsx import { useQuery, useMutation } from '@tanstack/react-query'; import { modelenceLiveQuery, modelenceMutation } from 'modelence/client'; import { useSession } from 'modelence/client'; export default function TodoList() { const { user } = useSession(); // Live query - automatically updates when todos change const { data: todos, isLoading } = useQuery( modelenceLiveQuery('todo.getAll', { userId: user?.id }) ); const { mutate: createTodo } = useMutation( modelenceMutation('todo.create') ); const { mutate: toggleComplete } = useMutation( modelenceMutation('todo.toggleComplete') ); if (isLoading) return
Loading...
; return (
    {todos?.map(todo => (
  • toggleComplete({ id: todo._id, isCompleted: !todo.isCompleted, })} /> {todo.title}
  • ))}
); } ``` With this setup, when any client creates or updates a todo, all connected clients see the changes immediately. ## Live Queries vs WebSockets | Feature | Live Queries | WebSockets | | - | - | - | | **Use case** | Automatic data sync with TanStack Query | Custom real-time messaging | | **Data flow** | Server watches data, pushes updates | Bidirectional messaging | | **Client API** | `useQuery(modelenceLiveQuery(...))` | `ClientChannel` + `joinChannel` | | **Server API** | `LiveData` with `fetch` + `watch` | `ServerChannel` + `broadcast` | | **Best for** | Lists, dashboards, any data-driven UI | Chat, notifications, collaborative editing | Live queries are built on top of WebSockets internally, but provide a higher-level abstraction for the common pattern of keeping query data in sync. ## Common Pitfalls ### Missing QueryClient connection If you see `Modelence: connect a QueryClient before using modelenceLiveQuery()`, you mounted your own `QueryClientProvider` without connecting it. Either drop your custom provider and let `renderApp` inject `ModelenceQueryProvider`, or connect your client explicitly: ```tsx theme={null} import { connectModelenceQueryClient } from 'modelence/client'; const queryClient = new QueryClient(); connectModelenceQueryClient(queryClient); ``` ### Returning plain data instead of LiveData If you see `Live query handler for 'X' must return a LiveData object`, your query handler is returning data directly. Wrap it in `LiveData`: ```typescript theme={null} // Wrong getAll: async () => { return await dbItems.fetch({}); }, // Correct getAll: async () => { return new LiveData({ fetch: async () => await dbItems.fetch({}), watch: ({ publish }) => { const changeStream = dbItems.watch(); changeStream.on('change', () => publish()); return () => changeStream.close(); }, }); }, ``` ### Forgetting to close change streams Always return a cleanup function from `watch` to close change streams. Without this, streams accumulate and may exhaust database connections: ```typescript theme={null} watch: ({ publish }) => { const changeStream = dbTodos.watch(); changeStream.on('change', () => publish()); return () => changeStream.close(); // Don't forget this! }, ``` ## Migrating from @modelence/react-query Since `modelence@0.15.0`, the query helpers live in `modelence/client`, and `renderApp` connects a `QueryClient` for you. Existing apps using `@modelence/react-query` keep working — this migration is optional — but new code should use the core imports. **1. Swap the import source.** The helpers are drop-in identical: ```diff theme={null} - import { modelenceQuery, modelenceLiveQuery, modelenceMutation } from '@modelence/react-query'; + import { modelenceQuery, modelenceLiveQuery, modelenceMutation } from 'modelence/client'; ``` **2. Drop the manual provider wiring (optional).** If you connected the client only to satisfy live queries, you can let `renderApp` inject `ModelenceQueryProvider` and remove the boilerplate: ```diff theme={null} - import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; - import { ModelenceQueryClient } from '@modelence/react-query'; import { renderApp } from 'modelence/client'; - const queryClient = new QueryClient(); - new ModelenceQueryClient().connect(queryClient); renderApp({ - routesElement: ( - {routes} - ), + loadingElement:
Loading…
, + routesElement: routes, }); ``` If you still need your own `QueryClient`, replace `new ModelenceQueryClient().connect(queryClient)` with `connectModelenceQueryClient(queryClient)` (the `ModelenceQueryClient` class is deprecated but still exported for compatibility). ## API Reference * [modelenceQuery](/api-reference/modelence/client/functions/modelenceQuery) - Standard (non-live) query helper * [modelenceLiveQuery](/api-reference/modelence/client/functions/modelenceLiveQuery) - Live query helper * [ModelenceQueryProvider](/api-reference/modelence/client/functions/ModelenceQueryProvider) - Auto-connecting provider * [Store](/api-reference/modelence/server/classes/Store) - Database store with `watch()` support # Quick Start Source: https://docs.modelence.com/quickstart ### Prerequisites > [accordion] Node.js > > [Node.js](https://nodejs.org/en/download/) version 18.0 or above > > * When installing Node.js, make sure to check all checkboxes related to dependencies > * Node.js installation includes NPM (Node Package Manager) which is required > * You can verify your installation by running: > > ```bash theme={null} > node --version > npm --version > ``` > > If you see version numbers displayed for both commands, you're ready to start building with Modelence! ### Create a new project ```bash theme={null} npx create-modelence-app@latest my-app cd my-app ``` This creates a `my-app` directory with a new Modelence app and installs its dependencies. For a breakdown of what's inside, see [Project Structure](/core-concepts/project-structure). ### Connect to Modelence Cloud ```bash theme={null} npx modelence@latest setup ``` Your browser opens so you can sign in to [Modelence Cloud](https://cloud.modelence.com) and pick or create the environment to connect to. The environment provisions a MongoDB database for your app, and setup writes its connection details to `.modelence.env`. See [Local Setup](/setup) for the details. ### Run the app ```bash theme={null} npx modelence@latest dev ``` This starts the development server at [http://localhost:3000/](http://localhost:3000/) (or the port you set in `.env`). ### Deploy ```bash theme={null} npx modelence@latest deploy ``` Your browser opens so you can pick or create the cloud environment to deploy to, and the app goes live on its URL once the deploy finishes. See [Deploy Setup](/deploy/setup) for the details. ### Next steps If you build with an AI coding agent, see [AI Coding Agents](/ai-coding-agents) to set up Claude Code, Cursor, or Codex with Modelence's coding rules and documentation access. # Custom Rate Limiting Source: https://docs.modelence.com/rate-limiting Modelence provides a built-in rate limiting system you can use to protect any mutation or query from abuse. Authentication endpoints come with [their own default limits](/authentication/rate-limiting). ## Defining Rate Limits You can define your own rate limits by adding a `rateLimits` array to a [Module](/api-reference/modelence/server/classes/Module). Each rule specifies a bucket name, the type of actor being limited (`ip` or `user`), a time window, and a maximum number of allowed calls within that window. ```typescript theme={null} import { Module } from 'modelence/server'; import { time } from 'modelence'; const myModule = new Module('myFeature', { rateLimits: [ { bucket: 'myAction', type: 'ip', window: time.minutes(15), // 15-minute window limit: 10, // max 10 calls per window }, ], // ... }); ``` Multiple rules can share the same bucket to enforce more than one window. All rules on a bucket are checked — if any one is exceeded, the call is rejected: ```typescript theme={null} rateLimits: [ { bucket: 'myAction', type: 'ip', window: time.minutes(1), limit: 3 }, // 3 per minute { bucket: 'myAction', type: 'ip', window: time.hours(1), limit: 20 }, // 20 per hour { bucket: 'myAction', type: 'ip', window: time.days(1), limit: 100 }, // 100 per day ], ``` ### Consuming a Rate Limit Call [`consumeRateLimit`](/api-reference/modelence/server/functions/consumeRateLimit) inside a mutation or query handler to check and increment the rate limit counter. It throws a [RateLimitError](/api-reference/modelence/index/classes/RateLimitError) automatically when any matching rule is exceeded: ```typescript theme={null} import { consumeRateLimit } from 'modelence/server'; // Inside a mutation handler: async function handleMyAction(args, { connectionInfo }) { await consumeRateLimit({ bucket: 'myAction', type: 'ip', value: connectionInfo.ip, }); // ... proceed with the action } ``` An optional `message` parameter lets you provide a user-facing error message instead of the default: ```typescript theme={null} await consumeRateLimit({ bucket: 'myAction', type: 'ip', value: connectionInfo.ip, message: 'Too many requests. Please wait a moment and try again.', }); ``` ## Reverse Proxy Deployments For backward compatibility, Modelence trusts the complete `X-Forwarded-For` chain when no proxy configuration is present. This preserves existing client IP behavior during upgrades, but callers can supply their own value. Production deployments should list only the proxy addresses or networks they control: ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ security: { trustedProxies: ['loopback', '10.0.0.0/8'], }, }); ``` For hosted deployments, the equivalent environment variable takes precedence over the `startApp()` setting: ```bash theme={null} MODELENCE_TRUSTED_PROXIES="loopback,10.0.0.0/8" ``` `trustedProxies` accepts IP addresses, CIDR ranges, and the Express named ranges `loopback`, `linklocal`, and `uniquelocal`. Modelence then walks the forwarded chain from the app toward the client and uses the first untrusted address. Forged values prepended by a caller do not become the IP rate-limit key. Configure the edge proxy to overwrite or append the actual peer address, and prevent untrusted clients from connecting directly to the application port. ### Cloudflare Cloudflare *appends* to an inbound `X-Forwarded-For` header rather than overwriting it, so its left-most value is chosen by the caller. Cloudflare therefore [recommends](https://developers.cloudflare.com/fundamentals/reference/http-headers/) reading `CF-Connecting-IP`, which always holds exactly one address. Set `clientIpHeader` to use it: ```typescript theme={null} startApp({ security: { trustedProxies: [/* Cloudflare's published IP ranges */], clientIpHeader: 'cf-connecting-ip', }, }); ``` `clientIpHeader` is only read when the connecting peer matches `trustedProxies`, so it must be configured alongside them with Cloudflare's [published IP ranges](https://www.cloudflare.com/ips/). Two caveats: * With the default trust-all behavior (neither `trustedProxies` nor `MODELENCE_TRUSTED_PROXIES` set), every peer counts as trusted, so anyone able to reach the application port directly could set the header themselves. Always pair `clientIpHeader` with an explicit trusted proxy list. * If the trusted list does not cover the full Cloudflare edge, requests through uncovered addresses fall back to the peer address, collapsing many clients onto a single rate-limit key. `True-Client-IP` works the same way, but is Enterprise-only and must be enabled via a Managed Transform. Cloudflare warns that in a stacked-CDN setup its value can be spoofed unless your own edge sets it. # React Native Source: https://docs.modelence.com/react-native > [!NOTE] > > React Native support is available from **modelence v0.19.0**. Modelence's client library works in React Native. Because React Native lacks browser APIs like `localStorage` and `window`, you configure the client with `configureClient` so the SDK knows how to store auth tokens, read device dimensions, and resolve server URLs. ## Setup **1. Install dependencies** Add Modelence to your React Native project: ```bash theme={null} npm install modelence ``` You'll also need `@react-native-async-storage/async-storage` (or any other persistent key-value store) to persist the auth token across app restarts. ```bash theme={null} npm install @react-native-async-storage/async-storage ``` **2. Configure the client** Call `configureClient` once, before your app mounts — for example at the top of your entry file (`App.tsx` or `index.ts`). ```typescript theme={null} import { configureClient } from 'modelence/client'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { Dimensions, Linking, PixelRatio } from 'react-native'; const AUTH_TOKEN_KEY = 'modelence_auth_token'; // getAuthToken is called synchronously on every request, so we keep the // token in memory and mirror writes to AsyncStorage for persistence across // app restarts. Load the persisted value before mounting your app (see // the loadAuthToken helper below). let authToken: string | undefined; export async function loadAuthToken() { authToken = (await AsyncStorage.getItem(AUTH_TOKEN_KEY)) ?? undefined; } configureClient({ baseUrl: 'https://your-modelence-app.com', getAuthToken: () => authToken, setAuthToken: (token) => { authToken = token ?? undefined; if (token === null) { AsyncStorage.removeItem(AUTH_TOKEN_KEY); } else { AsyncStorage.setItem(AUTH_TOKEN_KEY, token); } }, getClientInfo: () => { const screen = Dimensions.get('screen'); const window = Dimensions.get('window'); return { screenWidth: screen.width, screenHeight: screen.height, windowWidth: window.width, windowHeight: window.height, pixelRatio: PixelRatio.get(), orientation: screen.width > screen.height ? 'landscape' : 'portrait', }; }, // Used for OAuth redirects — opens the URL in the device browser openUrl: (url) => Linking.openURL(url), }); ``` **3. Wrap your app with AppProvider** Load the persisted auth token before mounting your app, then wrap your root component with `AppProvider`: ```tsx theme={null} import { AppProvider } from 'modelence/client'; import { loadAuthToken } from './modelenceConfig'; // the file from the previous step import { useEffect, useState } from 'react'; export default function App() { const [ready, setReady] = useState(false); useEffect(() => { loadAuthToken().then(() => setReady(true)); }, []); if (!ready) return null; return ( ); } ``` ## ClientConfig reference | Field | Type | Description | | - | - | - | | `baseUrl` | `string` | Absolute URL of your Modelence server, e.g. `https://myapp.com`. All API and WebSocket connections are made relative to this URL. | | `getAuthToken` | `() => string \| undefined` | Returns the stored auth token synchronously. Called before every request — must not return a `Promise`. | | `setAuthToken` | `(token: string \| null) => void` | Persists or clears the auth token synchronously. Called after login and logout. Async side-effects (e.g. writing to `AsyncStorage`) are fine as long as the function itself is not `async`. | | `getClientInfo` | `() => ClientInfo` | Returns device screen dimensions and pixel ratio. Used for telemetry. | | `openUrl` | `(url: string) => unknown` | *(Optional)* Opens a URL externally. Defaults to `window.location.href` assignment in browsers. Pass `Linking.openURL` for React Native OAuth redirects. On the web, return the result of `window.open` to run the flow in a popup — see [Embedded previews and popups](#embedded-previews-and-popups). | ## Using authentication Auth functions work the same way as on the web: ```typescript theme={null} import { loginWithPassword, logout, useSession } from 'modelence/client'; // Login await loginWithPassword({ email: 'user@example.com', password: 'secret' }); // Access current user function ProfileScreen() { const { user } = useSession(); if (!user) return Not logged in; return Hello, {user.handle}; } // Logout await logout(); // clears the stored token via setAuthToken(null) ``` ## Calling methods `callMethod` works without any changes — it automatically prepends `baseUrl` to every request: ```typescript theme={null} import { callMethod } from 'modelence/client'; const result = await callMethod('myModule.getData', { id: '123' }); ``` ## Live queries and WebSockets Live queries connect over WebSocket to `baseUrl`. No additional configuration is needed beyond `configureClient`: ```typescript theme={null} import { useQuery } from 'modelence/client'; import { myModule } from './modules/myModule'; function ItemList() { const items = useQuery(myModule.queries.listItems); return items?.map(item => {item.name}); } ``` ## OAuth sign-in > [!NOTE] > > Native OAuth sign-in is available from **modelence v0.23.0**. Google and GitHub sign-in run in the device browser and hand the result back to your app through a deep link. You register **one** redirect URI with the provider — the same one a web app uses — and Modelence routes the mobile flow through it. **1. Allowlist your deep link** The server only redirects to deep links you have explicitly allowed. Set `auth.mobile.redirectUrls` in `startApp`: ```typescript theme={null} startApp({ auth: { mobile: { redirectUrls: ['myapp://auth'] }, }, }); ``` Or as a comma-separated config value, manageable from Modelence Cloud or the environment: ```bash theme={null} MODELENCE_AUTH_MOBILE_REDIRECT_URLS=myapp://auth ``` Both sources are merged. Until at least one entry exists, mobile sign-in is rejected. **2. Start the flow** Pass the deep link your app listens on. `openUrl` must be configured (see Setup above). ```typescript theme={null} import { signInWithOAuth } from 'modelence/client'; await signInWithOAuth({ provider: 'google', redirectUri: 'myapp://auth' }); ``` > [!WARNING] > > The `redirectUri` must be **your app's own scheme**, and it must appear in > `auth.mobile.redirectUrls` verbatim. Passing a URL that merely reaches your > server — an Expo dev URL, or your site's own domain — is the most common way > this flow breaks. See [Choosing a redirect URI](#choosing-a-redirect-uri). **3. Complete the sign-in** When the flow finishes, Modelence redirects to `myapp://auth?code=...`. Exchange that code for a session: ```typescript theme={null} import { loginWithOAuth, parseDeepLinkParams } from 'modelence/client'; import { Linking } from 'react-native'; import { useEffect } from 'react'; useEffect(() => { const subscription = Linking.addEventListener('url', async ({ url }) => { const { code, error, errorCode } = parseDeepLinkParams(url); if (error) { // Sign-in failed. `errorCode` is stable and safe to branch on // (e.g. 'missing_code', 'invalid_state'); `error` is display text. return; } if (code) { await loginWithOAuth({ code }); // useSession() now reflects the signed-in user. } }); return () => subscription.remove(); }, []); ``` > [!NOTE] > > Use `parseDeepLinkParams` rather than `new URL(url).searchParams`. React > Native's built-in `URL` is a partial implementation that throws on > `searchParams`; Expo only works because it installs a polyfill. Handle the cold-start case too. If the app was closed when the deep link fired, the URL arrives via `Linking.getInitialURL()` and the `url` event never runs — so a sign-in that launches the app would silently do nothing: ```typescript theme={null} useEffect(() => { // Codes are single-use, so guard against handling the same one twice — // getInitialURL and the url event can both deliver it. const handled = new Set(); async function completeSignIn(url: string) { const { code } = parseDeepLinkParams(url); if (!code || handled.has(code)) return; handled.add(code); await loginWithOAuth({ code }); } // Cold start: the deep link launched the app. Linking.getInitialURL().then((url) => { if (url) completeSignIn(url); }); // Warm start: the app was already running. const subscription = Linking.addEventListener('url', ({ url }) => { completeSignIn(url); }); return () => subscription.remove(); }, []); ``` ### Choosing a redirect URI `redirectUri` is where the user should end up once the provider is done — whatever `Linking.createURL('auth')` returns for the target you are running on. Modelence issues a plain HTTP redirect to it, so what happens next depends on the scheme: | Redirect URI | Where it lands | What you need | | - | - | - | | `myapp://auth` | The app registered for `myapp://` | Native build (standalone or dev-client) | | `https://your-app…/auth` | A page load in your app | Expo Web: an `/auth` route in the router | | `exp://…/--/auth` | The app running under Expo Go | Expo Go: the host changes per machine | All three are valid. What they share is that **each needs its own entry in `auth.mobile.redirectUrls`**, because the value differs per target. Two errors follow, and they mean different things: **"This redirectUri is not in auth.mobile.redirectUrls."** The exact string you passed is not allowlisted. Log the value and add it verbatim — entries match on scheme, host and path, so a differing port or trailing path is a different target. **A 404 / "Unmatched Route" page with `?code=…` in the URL.** The redirect succeeded and sign-in worked — the code is real — but nothing is serving that path. On Expo Web this means the `/auth` route is missing; add it (see the next section). With a custom scheme it means the app was not installed or the scheme was not registered. ### Expo Web and `https://` redirect URIs Under Expo Web your app *is* a website, served from an `https://` origin, and `Linking.createURL('auth')` returns something like `https://your-app.example.com/auth`. That is a perfectly good redirect target — the same React Native code runs unchanged, and `Linking.openURL` navigates the current tab. Two things follow, and both are handled for you: * **The route must exist.** Unlike a custom scheme, an `https://` redirect is a real page load in your app. Expo Router needs an `/auth` route, or you get the "Unmatched Route" screen with `?code=…` in the URL. * **The verifier survives the navigation.** Leaving the page tears down the JavaScript context that minted the device-binding verifier, so Modelence mirrors it into `sessionStorage` in browsers and restores it on return. You do not need to do anything; the same `loginWithOAuth({ code })` call works. A minimal `app/auth.tsx` for Expo Router — the same handler as the native case, reading the code from the page URL: ```typescript theme={null} import { useEffect } from 'react'; import { router } from 'expo-router'; import { loginWithOAuth, parseDeepLinkParams } from 'modelence/client'; export default function AuthCallback() { useEffect(() => { const { code, error } = parseDeepLinkParams(window.location.href); if (error) return; // show it to the user if (code) loginWithOAuth({ code }).then(() => router.replace('/')); }, []); return Signing you in…; } ``` > [!NOTE] > > Each build target needs its own allowlist entry, because > `Linking.createURL('auth')` returns a different value in each — see the table > below. Add the Expo Web origin alongside your native scheme. ### Embedded previews and popups When your web build runs inside a **cross-origin iframe** — an embedded preview, a sandbox, a hosted playground — it cannot navigate in place: Google and GitHub refuse to render their consent screen inside an iframe. The flow has to run in a real top-level popup instead. Have `openUrl` open one and **return it**: ```typescript theme={null} configureClient({ // ... openUrl: (url) => window.open(url), }); ``` > [!NOTE] > > Framing is a prerequisite, and it is denied by default. Modelence sends > `X-Frame-Options: SAMEORIGIN` and CSP `frame-ancestors 'self'`, so an > embedding page on another origin gets a blocked frame before OAuth is ever > reached. List the embedding origin in > [`security.frameAncestors`](/api-reference/modelence/server/type-aliases/SecurityConfig#frameancestors) > first. That return value is what makes the popup case work. Once the popup is a top-level window, browsers partition its `sessionStorage` away from the iframe's (Chrome storage partitioning, Safari ITP), so the two contexts share nothing. The direction of the handoff is what decides where the user ends up signed in. The popup **hands the single-use code back to your page**, and your page — which still holds the verifier in memory — redeems it and completes the sign-in in its own context. The session therefore lands in the iframe, where your app actually runs, rather than in a popup that is about to close. The verifier never leaves the page that minted it, and no session token crosses `postMessage`. The callback route is the same `app/auth.tsx` as above. In the popup, `loginWithOAuth({ code })` finds no verifier of its own, hands the code to its opener, and resolves to `null` — there is no user to return there, and the popup is closed for you: ```typescript theme={null} const user = await loginWithOAuth({ code }); if (user) { // Signed in here: the ordinary same-tab or native flow. } else { // This was an embedded popup. The opening page completed the sign-in. } ``` A page that has its own verifier never consults an opener, so same-tab and native flows are unaffected. #### If the opening page reloads mid-flow An embedded preview that refreshes while the popup is still at the provider (a hot reload, a preview refresh) loses the in-memory listener that would receive the code. The verifier survives in `sessionStorage`, so hand the popup back on load to keep the flow alive: ```typescript theme={null} import { resumeOAuthPopup } from 'modelence/client'; // On load, reconnect to a popup opened with a name you can reclaim. const popup = window.open('', 'modelence-oauth'); if (popup) resumeOAuthPopup({ popup }); ``` `resumeOAuthPopup` returns `false` when no sign-in was pending, so it is safe to call unconditionally. > [!WARNING] > > The handoff relies on the popup keeping its `window.opener` across the > provider round trip. A provider page that sends > `Cross-Origin-Opener-Policy: same-origin` severs that link, in which case the > popup has nobody to hand the code to and the embedded flow cannot complete. > > This is not detectable from application code: a COOP `same-origin` response > moves the popup into a new browsing context group, clearing `window.name` > along with `window.opener`, so by the time your callback route runs there is > no evidence left that the page was ever a popup. The failure therefore > surfaces as the generic "no sign-in in progress" console message, which lists > COOP among its causes. If an embedded sign-in stalls and that message appears, > check the provider's response headers. > > Top-level (non-iframe) sign-in is unaffected, since there the verifier is read > from the page's own `sessionStorage` and no opener is involved. ### Plain web apps (no React Native) If you are building a plain web app with no native target, skip `redirectUri` entirely: ```typescript theme={null} await signInWithOAuth({ provider: 'google' }); ``` The callback sets a session cookie and returns the user to your site already signed in — no code to redeem, no callback route to write. ### Universal links An `https://` redirect can also be intercepted by the OS and handed to your **native app** instead of a browser, via [universal links](https://developer.apple.com/ios/universal-links/) or Android App Links. That needs an `apple-app-site-association` (iOS) or `assetlinks.json` (Android) served from the domain plus the matching associated-domain entitlement in the app. When configured, the URL arrives through the same `Linking` handler as a custom scheme and nothing else changes. A custom scheme (`myapp://auth`) is simpler if you do not already need universal links for other reasons. ### Expo: one entry per build target `Linking.createURL('auth')` returns a different value depending on how the app is running, and every one of them needs its own allowlist entry: | Environment | `Linking.createURL('auth')` returns | Stable? | | - | - | - | | Standalone / dev-client build | `myapp://auth` | Yes — hardcode it | | Expo Web | `https:///auth` | Per deployment host | | Expo Go | `exp://192.168.1.5:8081/--/auth` | No — varies per machine or tunnel | The Expo Go host follows your LAN address or tunnel, so it cannot be committed to `startApp`. That is why `auth.mobile.redirectUrls` is also readable from the environment and from Modelence Cloud — set the volatile ones there, per environment, without a redeploy: ```bash theme={null} MODELENCE_AUTH_MOBILE_REDIRECT_URLS=exp://192.168.1.5:8081/--/auth,https://your-preview-host/auth ``` Whatever the target, log the value and add that exact string: ```typescript theme={null} const redirectUri = Linking.createURL('auth'); console.log('OAuth redirectUri:', redirectUri); // paste this into the allowlist await signInWithOAuth({ provider: 'google', redirectUri }); ``` ### Why a code instead of a token The deep link carries a single-use code valid for one minute, not the session token. Custom URL schemes can be registered by more than one app on a device, so a token in the redirect could be picked up by an app that isn't yours. The code is exchanged for the real session over HTTPS in `loginWithOAuth`, and it cannot be redeemed twice. The code is also bound to the client that started the flow. `signInWithOAuth` mints a verifier and `loginWithOAuth` replays it, so a `myapp://auth?code=...` link handed to your app from anywhere else is rejected before the code is ever sent. The verifier is held in memory on native, and additionally mirrored into `sessionStorage` in browsers so that an Expo Web or plain-browser flow survives the navigation to the provider. It is cleared once redeemed, and when the tab closes. If the app process is killed mid-flow on native, the verifier is gone and the sign-in must be started again. ### Linking a provider to an existing account For an already signed-in user, `linkOAuthProvider` takes the same `redirectUri` so the flow returns to your app instead of ending in the browser: ```typescript theme={null} import { linkOAuthProvider } from 'modelence/client'; await linkOAuthProvider({ provider: 'github', redirectUri: 'myapp://auth' }); // returns to myapp://auth?linked=github ``` ## Notes * **No `AppProvider` required for auth-only usage.** You can call `loginWithPassword`, `callMethod`, etc. without `AppProvider`. The provider is needed only if you use React hooks like `useSession` or `useQuery`. * **Token persistence is your responsibility.** Modelence calls `setAuthToken` and `getAuthToken` but does not bundle a storage library. Use `AsyncStorage`, `expo-secure-store`, or any store that fits your security requirements. * **`orientation` in `ClientInfo` is optional.** Pass `null` if your app does not track orientation. # Roles Source: https://docs.modelence.com/roles Define custom roles and manage user access Modelence provides built-in support for user roles. You can define roles in `startApp`, assign them to users, and check them on both the server and client. ## Defining Roles Register the roles your app uses in your `startApp` call: ```typescript theme={null} import { startApp } from 'modelence/server'; startApp({ roles: { admin: { description: 'Full access to all features' }, editor: { description: 'Can edit content' }, viewer: {}, }, }); ``` Each role has an optional `description` that is shown in the Modelence Cloud dashboard. > [!NOTE] > > Roles defined in `startApp` are synced to Modelence Cloud so you can assign > them to users directly from the dashboard. ## Checking Roles in Handlers Use `user.requireRole` to throw an error if the user lacks a role, or `user.hasRole` for manual checking: ```typescript theme={null} import { Module } from 'modelence/server'; import { AuthError } from 'modelence'; export default new Module('myModule', { mutations: { adminAction: { handler: async (args, { user }) => { if (!user) { throw new AuthError('Not authenticated'); } // Throws if the user doesn't have the "admin" role user.requireRole('admin'); // Admin-only logic here } }, anotherAdminAction: { handler: async (args, { user }) => { if (!user) { throw new AuthError('Not authenticated'); } // Check without throwing for custom error handling if (!user.hasRole('admin')) { throw new Error('Admin access required'); } // Admin-only logic here } } } }); ``` ## Assigning Roles The recommended way to assign roles is through the Modelence Cloud user management dashboard. If that is not available, you can update roles directly via the `dbUsers` collection: ```typescript theme={null} import { dbUsers, ObjectId } from 'modelence/server'; // Add a role await dbUsers.updateOne( { _id: new ObjectId(userId) }, { $addToSet: { roles: 'admin' } } ); // Add multiple roles await dbUsers.updateOne( { _id: new ObjectId(userId) }, { $addToSet: { roles: { $each: ['editor', 'viewer'] } } } ); // Remove a role await dbUsers.updateOne( { _id: new ObjectId(userId) }, { $pull: { roles: 'admin' } } ); ``` ## Frontend Usage Use `useSession` to check roles on the client and conditionally render UI: ```typescript theme={null} import { useSession } from 'modelence/client'; function AdminPanel() { const { user } = useSession(); if (!user?.hasRole('admin')) { return
Access denied
; } return
Admin content
; } ``` ```typescript theme={null} import { useSession } from 'modelence/client'; function Navigation() { const { user } = useSession(); return ( ); } ``` ## API Reference **`startApp` options:** * `roles` — `Record` — role definitions keyed by name **`RoleDefinition`:** * `description?: string` — optional human-readable description shown in the Modelence Cloud dashboard **User methods:** * `user.roles: string[]` — the roles assigned to the user * `user.hasRole(role: string): boolean` — check if user has a specific role * `user.requireRole(role: string): void` — throw error if user doesn't have role # Local Setup Source: https://docs.modelence.com/setup Connect a project running on your machine to a Modelence local environment This page is written for a coding agent. It describes what a local environment is and the steps to connect a project to one. If you are a person, hand it to your agent: ```text theme={null} Use https://docs.modelence.com/setup.md to connect this project to a Modelence local environment ``` ## What a local environment is * **The app runs on the user's machine**, started from the project directory. Modelence does not build or host it; to put the app online, deploy it to a cloud environment as described in [Deploy Setup](/deploy/setup). * **The environment holds what the app uses**: the connection strings of its resources (databases, caches) and its settings. They reach the app when it starts, so they never need to be copied into the project. * **The dashboard shows the running app** on the environment's **Overview**, so the user can see whether it is up. ## Connecting a project 1. **Run `npx modelence@latest setup`** in the project root, with a timeout of at least 10 minutes. It opens the browser, where the user signs in and picks the organization, application and environment, or creates a new application or environment there. Tell the user to confirm there, then wait for the command to finish. Pass `--new` when the user wants a new environment rather than an existing one. 2. **Tell the user the project is connected**, and that they start it by running `npx modelence@latest dev` in the project directory, in place of the project's own development command. Do not start it yourself unless the user asks you to. Once it runs, the environment's **Overview** in the Modelence dashboard shows it. # Server-Side Rendering Source: https://docs.modelence.com/ssr Render your React tree on the server for faster first paint and hydrate on the client. Available since modelence@0.15.0. Server-side rendering (SSR) renders your React application to HTML on the server, sends that HTML to the browser, and then hydrates it on the client. This improves first-paint performance and lets crawlers see fully rendered markup. SSR in Modelence is **opt-in**. Existing client-only apps keep working unchanged — you only get SSR after you explicitly enable it. ## Enabling SSR Set `ssr: true` in `startApp`: ```typescript title="src/server/app.ts" theme={null} import { startApp } from 'modelence/server'; import todoModule from './todo'; startApp({ modules: [todoModule], ssr: true, }); ``` That's the only required change. The Modelence build always emits SSR artifacts, so there is no separate build flag — `startApp({ ssr: true })` decides whether they are used at runtime. > [!NOTE] > > When `ssr` is omitted or `false`, Modelence renders on the client only, exactly as > before. Nothing about your existing app changes until you opt in. ## Routing with SSR For the server and client to resolve the same route, a location-driven router must be told which URL to render. Pass a `router` function to `renderApp`. Modelence calls it with the current `location` on the server and again on the client during hydration, so both produce the same tree: ```tsx title="src/client/index.tsx" theme={null} import { renderApp } from 'modelence/client'; import { StaticRouter } from 'react-router-dom/server'; import { BrowserRouter } from 'react-router-dom'; import routes from './routes'; renderApp({ loadingElement:
Loading…
, routesElement: routes, router: ({ children, location }) => typeof window === 'undefined' ? {children} : {children}, }); ``` The `location` passed to the router is `path + search` (the hash is never sent to the server), matching what the browser sees on hydration. This avoids hydration mismatches. > [!WARNING] > > Without a `router`, a location-driven router (like React Router) will render its > default route on the server and a different route on the client, producing a > hydration mismatch. Only pass `router` when your routing depends on the current > URL. ## Data fetching and hydration * **Session** is rendered on the server and hydrated on the client, so `useSession()` returns the correct value on the very first render with no flash of logged-out UI. * **Queries** (`modelenceQuery`) run on the server and their results are serialized into the HTML, so cached data is available immediately after hydration. * **Live queries** (`modelenceLiveQuery`) are WebSocket subscriptions with no server snapshot — they stay pending during SSR and connect after hydration on the client. See [Queries](/core-concepts/queries) and [Live Queries](/live-queries) for how to call methods from the client. ## Related * [Queries](/core-concepts/queries) * [Live Queries](/live-queries) * [Project Structure](/core-concepts/project-structure) # Stores Source: https://docs.modelence.com/stores MongoDB collections with TypeScript schemas and helper methods Stores in Modelence provide a type-safe interface for MongoDB collections with built-in schema validation, custom methods, and indexing support. ## Overview A Store represents a MongoDB collection with: * **Type-safe schemas** using Modelence schema types (based on Zod) * **Custom document methods** for business logic * **MongoDB indexes** for query performance * **Search indexes** for MongoDB Atlas Search * **CRUD operations** with full TypeScript support ## Creating a Store Define a Store by specifying a collection name and configuration: ```typescript theme={null} import { Store, schema } from 'modelence/server'; export const dbTodos = new Store('todos', { schema: { title: schema.string(), isCompleted: schema.boolean(), dueDate: schema.date().optional(), userId: schema.userId(), createdAt: schema.date(), }, indexes: [ { key: { userId: 1 } }, { key: { dueDate: 1 } }, ], methods: { isOverdue() { return this.dueDate ? this.dueDate < new Date() : false; } } }); ``` ## Schema Definition Modelence schemas are based on and closely resemble Zod types. Available schema types include: ```typescript theme={null} { // Primitive types name: schema.string(), age: schema.number(), isActive: schema.boolean(), createdAt: schema.date(), // Optional fields description: schema.string().optional(), // Arrays tags: schema.array(schema.string()), // Objects metadata: schema.object({ key: schema.string(), value: schema.string(), }), // Built-in Modelence types userId: schema.userId(), // References a user ID } ``` ## Custom Methods Add custom methods to documents for business logic: ```typescript theme={null} export const dbProducts = new Store('products', { schema: { name: schema.string(), price: schema.number(), discount: schema.number().optional(), }, methods: { getFinalPrice() { return this.discount ? this.price * (1 - this.discount / 100) : this.price; }, hasDiscount() { return !!this.discount && this.discount > 0; } } }); // Usage const product = await dbProducts.findById(productId); console.log(product.getFinalPrice()); // Custom method available ``` ## Indexes For index configuration and examples, see [Indexes](/indexes). The indexes guide covers: * MongoDB `indexes` * Atlas `searchIndexes` * `indexCreationMode` (`blocking` vs `background`) and startup behavior with migrations ## CRUD Operations Stores provide comprehensive methods for data operations: ### Finding Documents ```typescript theme={null} // Find one document const todo = await dbTodos.findOne({ userId: user.id }); // Find by ID const todo = await dbTodos.findById(todoId); // Require one (throws error if not found) const todo = await dbTodos.requireById(todoId); // Fetch multiple documents const todos = await dbTodos.fetch( { userId: user.id }, { projection: { title: 1, isCompleted: 1, createdAt: 1 }, sort: { createdAt: -1 }, limit: 10 } ); // Exclude heavy fields when they are not needed const chunks = await dbDocumentChunks.fetch( { documentId }, { projection: { embedding: 0 } } ); // Count documents const count = await dbTodos.countDocuments({ isCompleted: false }); ``` ### Inserting Documents ```typescript theme={null} // Insert one const { insertedId } = await dbTodos.insertOne({ title: 'Buy groceries', isCompleted: false, userId: user.id, createdAt: new Date() }); // Insert many const result = await dbTodos.insertMany([ { title: 'Task 1', isCompleted: false, userId: user.id, createdAt: new Date() }, { title: 'Task 2', isCompleted: false, userId: user.id, createdAt: new Date() } ]); ``` ### Updating Documents ```typescript theme={null} // Update one await dbTodos.updateOne( { _id: new ObjectId(todoId) }, { $set: { isCompleted: true } } ); // Update one with convenience selector (by ID string) await dbTodos.updateOne( todoId, { $set: { isCompleted: true } } ); // Upsert (update or insert) await dbTodos.upsertOne( { userId: user.id, title: 'Unique task' }, { $set: { isCompleted: false } } ); // Atomic find-or-create — returns the document and whether it was just created const { doc, isNew } = await dbTodos.findOneAndUpsert( { userId: user.id, title: 'Unique task' }, { $setOnInsert: { userId: user.id, title: 'Unique task', isCompleted: false } } ); if (isNew) { // ...run first-time setup for the new document } // Update many await dbTodos.updateMany( { userId: user.id }, { $set: { isArchived: true } } ); ``` > [!NOTE] > > `findOneAndUpsert` is the atomic form of a check-then-create: it matches or inserts in a single operation and reports `isNew` (from the driver's upsert result), so concurrent callers can't race between a lookup and an insert. Pass `upsert: false` to make it a pure find-and-report that returns `{ doc: null, isNew: false }` when nothing matches. It always returns the post-operation document. ### Deleting Documents ```typescript theme={null} // Delete one await dbTodos.deleteOne({ _id: new ObjectId(todoId) }); // Delete many await dbTodos.deleteMany({ isCompleted: true }); ``` ### Advanced Operations ```typescript theme={null} // Aggregation pipeline const stats = await dbTodos.aggregate([ { $match: { userId: user.id } }, { $group: { _id: '$isCompleted', count: { $sum: 1 } }} ]).toArray(); // Bulk write operations await dbTodos.bulkWrite([ { insertOne: { document: { title: 'New task', /* ... */ } } }, { updateOne: { filter: { _id: new ObjectId(todoId) }, update: { $set: { isCompleted: true } } } }, { deleteOne: { filter: { _id: new ObjectId(oldTodoId) } } } ]); ``` ## Including Stores in Modules Register stores in your module to automatically provision them: ```typescript theme={null} import { Module } from 'modelence/server'; import { dbTodos } from './db'; export default new Module('todo', { stores: [dbTodos], queries: { async getAll() { return await dbTodos.fetch({}); } } }); ``` When your application starts, Modelence will: * Provision the collection in MongoDB * Create all configured indexes * Create all configured search indexes > [!TIP] > > Stores handle all MongoDB connection management automatically. Just define your Store and include it in a module - Modelence takes care of the rest. ## Extending Stores Use the `extend()` method to add custom schema fields, indexes, methods, and search indexes to any store, including system collections: ```typescript theme={null} import { schema, dbUsers } from 'modelence/server'; // Extend the users collection export const extendedDbUsers = dbUsers.extend({ schema: { firstName: schema.string(), lastName: schema.string(), companyId: schema.objectId().optional(), }, indexes: [ { key: { companyId: 1 } }, { key: { lastName: 1, firstName: 1 } }, ], methods: { getFullName() { return `${this.firstName} ${this.lastName}`; } } }); // Fully typed with new fields and methods! const user = await extendedDbUsers.findOne({ firstName: 'John' }); console.log(user?.getFullName()); // ✅ Custom methods work console.log(user?.companyId); // ✅ Type-safe fields console.log(user?.handle); // ✅ Original fields preserved ``` > [!NOTE] > > The `extend()` method creates a new Store instance with merged schema, methods, indexes, and search indexes. The extended store shares the same MongoDB collection as the original. ## Best Practices 1. **Define stores per domain** - Keep related data in the same module 2. **Plan index strategy** - See [Indexes](/indexes) for configuration patterns and startup mode tradeoffs 3. **Leverage custom methods** - Encapsulate business logic in document methods 4. **Type safety** - Let TypeScript guide you with schema-based types 5. **Use Atlas Search intentionally** - Use `searchIndexes` for advanced full-text search use cases 6. **Extend system collections early** - Extend system collections like `dbUsers` before using them in your application 7. **Use sparse indexes** - For optional fields with low cardinality, use `sparse: true` to save space ## API Reference For a complete list of available methods and detailed API documentation, see the [Store API Reference](/api-reference/modelence/server/classes/Store). # Telemetry Source: https://docs.modelence.com/telemetry Logging and monitoring your Modelence application Modelence includes built-in telemetry and logging functionality to help you monitor and debug your application. This guide covers the logging functions and environment variables you can use to control telemetry behavior. ## Logging Functions Modelence provides three logging functions for different severity levels. These functions automatically integrate with your telemetry provider when enabled, while also supporting console output for local development. ### logDebug Use `logDebug` for detailed debugging information that is typically only useful during development or troubleshooting. ```typescript theme={null} import { logDebug } from 'modelence/telemetry'; logDebug('Processing user request', { userId: user.id, action: 'profile_update' }); ``` **When it logs:** * To telemetry provider: Always (when telemetry is enabled) * To console: Only when `MODELENCE_LOG_LEVEL=debug` ### logInfo Use `logInfo` for general informational messages about application flow and important events. ```typescript theme={null} import { logInfo } from 'modelence/telemetry'; logInfo('User authenticated successfully', { userId: user.id, method: 'password' }); ``` **When it logs:** * To telemetry provider: Always (when telemetry is enabled) * To console: When `MODELENCE_LOG_LEVEL=debug` or `MODELENCE_LOG_LEVEL=info` ### logError Use `logError` for error conditions and exceptions that need attention. ```typescript theme={null} import { logError } from 'modelence/telemetry'; logError('Failed to process payment', { userId: user.id, error: error.message, orderId: order.id }); ``` **When it logs:** * To telemetry provider: Always (when telemetry is enabled) * To console: When `MODELENCE_LOG_LEVEL=debug`, `MODELENCE_LOG_LEVEL=info`, or `MODELENCE_LOG_LEVEL=error` ## Function Signature All three logging functions accept the same parameters: ```typescript theme={null} logDebug(message: string, args: object) logInfo(message: string, args: object) logError(message: string, args: object) ``` * **message**: A descriptive string explaining what is being logged * **args**: An object containing contextual data (user IDs, request details, etc.) ## Environment Variables ### `MODELENCE_LOG_LEVEL` Controls the verbosity of console logging. This is especially useful during local development or when debugging production issues. **Valid values:** * `debug` - Logs all messages (debug, info, and error) to console * `info` - Logs info and error messages to console * `error` - Logs only error messages to console * Not set - No console logging (default when telemetry is enabled) **Default behavior:** * When telemetry is **enabled** and `MODELENCE_LOG_LEVEL` is **not set**: No console logging * When telemetry is **disabled** and `MODELENCE_LOG_LEVEL` is **not set**: Defaults to `info` level **Example usage:** ```bash theme={null} # In your .env file or shell MODELENCE_LOG_LEVEL=debug ``` ```bash theme={null} # For development - see all logs MODELENCE_LOG_LEVEL=debug npx modelence@latest dev # For production debugging - see info and errors only MODELENCE_LOG_LEVEL=info npm start # For production monitoring - see only errors MODELENCE_LOG_LEVEL=error npm start ``` ## Log Level Behavior Matrix | Log Level | logDebug console | logInfo console | logError console | Telemetry | | - | - | - | - | - | | `debug` | ✓ | ✓ | ✓ | ✓ (if enabled) | | `info` | ✗ | ✓ | ✓ | ✓ (if enabled) | | `error` | ✗ | ✗ | ✓ | ✓ (if enabled) | | Not set (telemetry enabled) | ✗ | ✗ | ✗ | ✓ | | Not set (telemetry disabled) | ✗ | ✓ | ✓ | ✗ | ## Additional Telemetry Functions Modelence also provides advanced telemetry functions for performance monitoring and error tracking: ### startTransaction Track performance of operations like routes, methods, or background jobs: ```typescript theme={null} import { startTransaction } from 'modelence/telemetry'; const transaction = startTransaction('method', 'processOrder', { orderId: order.id }); try { // Your operation here await processOrder(order); transaction.end('success'); } catch (error) { transaction.end('failure'); throw error; } ``` **Transaction types:** * `method` - API method calls * `route` - HTTP route handlers * `cron` - Scheduled jobs * `ai` - AI operations * `custom` - Custom operations ### captureError Capture and report errors to your telemetry provider: ```typescript theme={null} import { captureError } from 'modelence/telemetry'; try { await riskyOperation(); } catch (error) { captureError(error); // Handle error... } ``` When telemetry is disabled, `captureError` falls back to `console.error`. ## Best Practices 1. **Use appropriate log levels**: Reserve `logError` for actual errors, use `logInfo` for important events, and `logDebug` for detailed troubleshooting information. 2. **Include context**: Always provide relevant context in the `args` object to make debugging easier: ```typescript theme={null} logInfo('Order processed', { orderId: order.id, userId: user.id, amount: order.total, paymentMethod: order.paymentMethod }); ``` 3. **Avoid logging sensitive data**: Never log passwords, API keys, or personally identifiable information (PII): ```typescript theme={null} // ❌ Bad logDebug('User login', { password: user.password }); // ✓ Good logDebug('User login', { userId: user.id, method: 'password' }); ``` 4. **Use transactions for performance tracking**: Wrap important operations in transactions to monitor their performance and success rates. 5. **Configure log levels per environment**: * **Development**: `MODELENCE_LOG_LEVEL=debug` for maximum visibility * **Staging**: `MODELENCE_LOG_LEVEL=info` for important events * **Production**: No `MODELENCE_LOG_LEVEL` set (rely on telemetry) or `MODELENCE_LOG_LEVEL=error` for critical issues only ## Telemetry Integration By default, Modelence logs are sent to your configured telemetry provider (like Modelence Cloud). To configure telemetry for your application: 1. Visit [cloud.modelence.com](https://cloud.modelence.com) 2. Select your project and environment 3. Navigate to **Application** → **Telemetry** settings 4. Configure your telemetry preferences All logging functions (`logDebug`, `logInfo`, `logError`) automatically send data to your telemetry provider when it's enabled, giving you centralized visibility into your application's behavior. ## Next Steps * Learn about [Authentication](/authentication) to add user management * Explore [Email](/email) configuration for transactional emails * Review [WebSockets](/websockets) for real-time features # Todo App Source: https://docs.modelence.com/tutorial Build a simple Todo app with Modelence In this tutorial, we'll build a complete Todo app using Modelence. You'll learn how to: * Create **MongoDB stores** with TypeScript schemas * Build **modules** with queries and mutations * Create **React components** that interact with your backend > [!NOTE] > > This tutorial assumes you've already [created a Modelence project](/quickstart) and [completed the setup](/setup). If you haven't done so, please complete those steps first. ## Step 1: Create a Todo Store Stores in Modelence are MongoDB collections with built-in TypeScript support, schema and helper methods. They help you to: * Define **type-safe schemas** for your data * Handle **CRUD operations** with MongoDB * Add **custom methods** to your documents * Configure **indexes** for better performance ### Set up the project structure The recommended approach in Modelence is to group code by modules/domains into separate directories. For our Todo app, create an `src/server/todo` directory and add a `db.ts` file: ```typescript title="src/server/todo/db.ts" theme={null} import { Store, schema } from 'modelence/server'; export const dbTodos = new Store('todos', { // Define the schema for your documents. Modelence schema is based on and closely resembles Zod types. schema: { title: schema.string(), isCompleted: schema.boolean(), dueDate: schema.date().optional(), userId: schema.userId(), // Built-in Modelence type for user references createdAt: schema.date(), }, // Configure MongoDB indexes indexes: [ { key: { userId: 1 } }, { key: { dueDate: 1 } }, ], // Add custom methods to documents. These are available on instances // returned by server-side Store methods (e.g. findById, fetch). // They are stripped when data is serialized over the wire to the client. methods: { isOverdue() { return this.dueDate ? this.dueDate < new Date() : false; } } }); ``` ### Using the Store Once defined, you can use your Store object to perform operations on your collection: ```typescript theme={null} const { insertedId } = await dbTodos.insertOne({ title: 'Buy groceries', isCompleted: false, dueDate: new Date('2023-01-31'), userId: '123', createdAt: new Date() }); const todo = await dbTodos.findById(insertedId); console.log(todo.isOverdue()); ``` ### Working with Documents Stores provide a comprehensive set of methods for working with MongoDB documents, including finding, inserting, updating, and deleting records. All methods are fully typed with TypeScript. See the [Store API Reference](/api-reference/modelence/server/classes/Store) for a complete list of available methods and their usage. > [!TIP] > > Stores automatically handle MongoDB connection management, collection provisioning and index creation. Just define your Store and start using it - Modelence takes care of the rest. ## Step 2: Create a Todo Module Modules are the core building blocks of a Modelence application. They help you organize your application's functionality into cohesive units that can contain queries, mutations, stores, cron jobs and configurations. Create a new file at `src/server/todo/index.ts`: ```typescript title="src/server/todo/index.ts" theme={null} import { Module } from 'modelence/server'; import { dbTodos } from './db'; export default new Module('todo', { /* Include the store we created earlier so it will be automatically provisioned in MongoDB when the server starts. */ stores: [dbTodos], /* Module queries and mutations are similar to the corresponding concepts from GraphQL. */ queries: { async getOne({ id }) { return await dbTodos.findById(id); }, async getAll() { return await dbTodos.fetch({}); } }, mutations: { async create({ title, dueDate }, { user }) { const { insertedId } = await dbTodos.insertOne({ title, dueDate, userId: user.id, isCompleted: false, createdAt: new Date() }); return insertedId; }, async update({ id, title, dueDate, isCompleted }) { return await dbTodos.updateOne(id, { $set: { title, dueDate, isCompleted } }); }, async delete({ id }) { return await dbTodos.deleteOne(id); } }, }); ``` ### Include the Module Now, add the Module to your main server file at `src/server/app.ts`: ```typescript title="src/server/app.ts" theme={null} import { startApp } from 'modelence/server'; import todoModule from './todo'; startApp({ modules: [todoModule] }); ``` As soon as your app starts, Modelence will: * Provision the `dbTodos` store in MongoDB * Make the queries and mutations available for calling ## Step 3: Create the Frontend Modelence is frontend-agnostic, so you are free to use any routing library you like. We will use React Router for this example, which is what's included in the default Modelence starter. ### Add a new route Edit `src/client/routes.ts` to add a new route for our todos: ```typescript title="src/client/routes.ts" theme={null} import { lazy } from 'react'; export const routes = [ // ... your existing routes { path: '/todos', Component: lazy(() => import('./TodosPage')) }, ]; ``` ### Create the TodosPage component Create a new component at `src/client/TodosPage.tsx`: ```tsx title="src/client/TodosPage.tsx" theme={null} import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { modelenceQuery, modelenceMutation, createQueryKey } from 'modelence/client'; // Helper: Store `methods` only live on server-side document instances and // are stripped when results are serialized over the wire. Reimplement // `isOverdue` on the client against the plain JSON shape. function isOverdue(todo: { dueDate?: string | Date | null }): boolean { if (!todo.dueDate) return false; return new Date(todo.dueDate) < new Date(); } export default function TodosPage() { const [newTodoTitle, setNewTodoTitle] = useState(''); const queryClient = useQueryClient(); const { data: todos, isPending: isLoading, error } = useQuery( modelenceQuery('todo.getAll') ); // `modelenceQuery('todo.getAll')` uses queryKey `['todo.getAll', {}]`, so // invalidation must match that exact shape. `createQueryKey` builds it // for us — passing `['todo.getAll']` would silently no-op. const invalidateTodos = () => { queryClient.invalidateQueries({ queryKey: createQueryKey('todo.getAll') }); }; const { mutate: createTodo, isPending: isCreating } = useMutation({ ...modelenceMutation('todo.create'), onSuccess: () => { setNewTodoTitle(''); invalidateTodos(); }, }); const { mutate: updateTodo } = useMutation({ ...modelenceMutation('todo.update'), onSuccess: invalidateTodos, }); const { mutate: deleteTodo } = useMutation({ ...modelenceMutation('todo.delete'), onSuccess: invalidateTodos, }); const handleCreateTodo = (e: React.FormEvent) => { e.preventDefault(); const title = newTodoTitle.trim(); if (!title) return; createTodo({ title }); }; const handleToggleComplete = (todo: any) => { updateTodo({ id: todo._id, title: todo.title, dueDate: todo.dueDate, isCompleted: !todo.isCompleted }); }; const handleDeleteTodo = (id: string) => { deleteTodo({ id }); }; if (isLoading) { return (
Loading todos...
); } if (error) { return (
Error: {error.message}
); } return (

My Todos

{/* Add new todo form */}
setNewTodoTitle(e.target.value)} placeholder="Add a new todo..." className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
{/* Todos list */}
{todos?.length === 0 ? (

No todos yet. Add one above!

) : ( todos?.map((todo) => (
handleToggleComplete(todo)} className="w-5 h-5 text-blue-600" /> {todo.title} {todo.dueDate && ( Due: {new Date(todo.dueDate).toLocaleDateString()} )}
)) )}
); } ``` ## Complete Example Want to see the full working code? Check it out on GitHub, along with other examples: > [card] [Complete Todo App Example](https://github.com/modelence/examples/tree/main/todo-app) > > See the complete source code for this tutorial on GitHub, including all files and additional features. # Voyage AI Source: https://docs.modelence.com/voyage-ai Build semantic search with Modelence, MongoDB and Voyage AI In this tutorial, you'll learn how to integrate Voyage AI with Modelence to build powerful semantic search capabilities. You'll learn how to: * Generate **embeddings** using Voyage AI's embedding models * Store embeddings in **MongoDB** using vector fields * Perform **vector search** with MongoDB's vector search capabilities * Use **reranking** to improve search results > [!NOTE] > > This tutorial assumes you've already [created a Modelence project](/quickstart) and [completed the setup](/setup). If you haven't done so, please complete those steps first. ## What is Voyage AI? Voyage AI provides state-of-the-art embedding and reranking models that enable semantic search, recommendation systems, and RAG (Retrieval-Augmented Generation) applications. Their models are optimized for: * **High-quality embeddings** for semantic similarity * **Reranking** to improve search result relevance * **Domain-specific fine-tuning** options ## Prerequisites Before starting, you'll need: 1. A Voyage AI API key - [Get one here](https://www.voyageai.com/) 2. A Modelence account with MongoDB configured ## Quick Start with Template The fastest way to get started is using the Voyage AI template: ```bash theme={null} npx degit modelence/examples/voyage-ai my-voyage-app cd my-voyage-app npm install ``` This creates a ready-to-use project with all the code from this tutorial pre-configured. ### Setup Steps 1. **Create an account** on [cloud.modelence.com](https://cloud.modelence.com/) 2. **Create an application and local environment** in the Modelence Cloud dashboard 3. **Open the Settings page** of your environment and click on **Setup Local Environment** 4. **Copy the command** from the "Connect to Modelence Cloud" section and execute it in your project directory 5. **Add your Voyage AI API key**: * Get your API key from [voyageai.com](https://www.voyageai.com/) * In the Modelence Cloud dashboard, open your environment's **Application** tab and set the `voyage.apiKey` config to your API key 6. **Run the project**: ```bash theme={null} npx modelence@latest dev ``` > [!TIP] > > You can also view a [live demo](https://voyage-ai-mg8435n3pj5-sandbox.prod.modelence.app) of the complete example. ## Manual Setup If you want to add Voyage AI to an existing project, follow these steps: ## Step 1: Install Dependencies Install the Voyage AI client library: ```bash theme={null} npm install voyageai ``` ## Step 2: Create a Document Store with Vector Embeddings Stores in Modelence support vector embeddings out of the box with the `schema.embedding()` type and vector search indexes. Create a new directory `src/server/voyage` and add a `db.ts` file: ```typescript title="src/server/voyage/db.ts" theme={null} import { Store, schema } from 'modelence/server'; export const dbDocuments = new Store('documents', { schema: { content: schema.string(), metadata: schema.object({ title: schema.string(), description: schema.string(), }), embedding: schema.embedding(), createdAt: schema.date(), }, indexes: [ { key: { createdAt: -1 } }, ], searchIndexes: [ Store.vectorIndex({ field: 'embedding', dimensions: 1024, // Voyage-3.5 default (supports 256, 512, 1024, 2048) }), ], }); ``` > [!TIP] > > The `schema.embedding()` type is a special type for storing vector embeddings. The `vectorIndex()` method creates a MongoDB vector search index for fast similarity searches. ## Step 3: Create Voyage AI Helper Functions Create a `voyage.ts` file to handle embedding generation and reranking: ```typescript title="src/server/voyage/voyage.ts" theme={null} import { getConfig } from 'modelence/server'; import { VoyageAIClient } from 'voyageai'; let voyageClient: VoyageAIClient | null = null; export function getVoyageClient() { if (!voyageClient) { const apiKey = getConfig('voyage.apiKey') as string || process.env.VOYAGE_API_KEY; if (!apiKey) { throw new Error('VOYAGE_API_KEY environment variable is not set'); } voyageClient = new VoyageAIClient({ apiKey }); } return voyageClient; } export async function generateEmbedding( text: string, inputType: 'query' | 'document' = 'document' ): Promise { const client = getVoyageClient(); const result = await client.embed({ input: [text], model: 'voyage-3.5', inputType, }); return result.data?.[0].embedding || []; } export async function rerank>( results: T[], field: string, query: string ) { const client = getVoyageClient(); const rerankedResponse = await client.rerank({ model: 'rerank-2.5', query: query, documents: results.map(doc => doc[field]), topK: 10, }); // Map the reranked results back to the original documents return rerankedResponse.data?.map(rerankedDoc => { const index = rerankedDoc.index || 0; return { ...results[index], score: rerankedDoc.relevanceScore }; }) || results; } ``` ### Key Points: * **Input Type**: Voyage AI supports different input types (`query` vs `document`) to optimize embeddings for different use cases * **Model Selection**: `voyage-3.5` is the latest embedding model supporting 4 dimension options (256, 512, 1024 default, and 2048). See all available [embedding models](https://docs.voyageai.com/docs/embeddings) * **Reranking**: Improves search results by reordering them based on relevance to the query. See all available [reranker models](https://docs.voyageai.com/docs/reranker) ## Step 4: Create a Module with Search Capabilities Create an `index.ts` file to tie everything together: ```typescript title="src/server/voyage/index.ts" theme={null} import { Module, ObjectId } from 'modelence/server'; import { z } from 'zod'; import { dbDocuments } from './db'; import { generateEmbedding, rerank } from './voyage'; export default new Module('voyage', { stores: [dbDocuments], queries: { async getDocuments() { return dbDocuments.fetch({}, { sort: { createdAt: -1 }, limit: 50, }); }, async searchSimilar(args) { const { query } = z.object({ query: z.string(), }).parse(args); // Generate embedding for the query const queryEmbedding = await generateEmbedding(query, 'query'); // Perform vector search using MongoDB const results = await (await dbDocuments.vectorSearch({ field: 'embedding', embedding: queryEmbedding, numCandidates: 100, limit: 10, projection: { content: 1, metadata: 1, createdAt: 1, }, })).toArray(); // Rerank results for better relevance return await rerank(results, 'content', query); }, }, mutations: { async addDocument(args) { const { title, description } = z.object({ title: z.string().min(1), description: z.string().min(1), }).parse(args); // Combine title and description for embedding const content = `${title}\n${description}`; // Generate embedding for the document const embedding = await generateEmbedding(content, 'document'); const result = await dbDocuments.insertOne({ content, metadata: { title, description, }, embedding, createdAt: new Date(), }); return { id: result.insertedId.toString(), content, metadata: { title, description }, createdAt: new Date(), }; }, async deleteDocument(args) { const { id } = z.object({ id: z.string(), }).parse(args); await dbDocuments.deleteOne({ _id: new ObjectId(id) }); return { success: true }; }, }, configSchema: { // 'secret' values are always server-only and masked in the Cloud dashboard; isPublic is not allowed. apiKey: { type: 'secret', default: '', }, }, }); ``` ### Understanding Vector Search The `vectorSearch()` method performs semantic search using MongoDB's vector search capabilities: * **field**: The field containing the embedding vectors * **embedding**: The query embedding to search for * **numCandidates**: Number of candidates to consider (higher = more accurate but slower) * **limit**: Maximum number of results to return * **projection**: Fields to include in results ## Step 5: Include the Module Add the Voyage module to your main server file: ```typescript title="src/server/app.ts" theme={null} import { startApp } from 'modelence/server'; import voyageModule from './voyage'; startApp({ modules: [voyageModule] }); ``` ## Step 6: Configure the API Key You can configure the Voyage AI API key in two ways: ### Option 1: Environment Variable Add to your `.env` file: ```bash theme={null} VOYAGE_API_KEY=your_api_key_here ``` ### Option 2: Module Config Store it securely in MongoDB using Modelence's config system: ```typescript theme={null} import { setConfig } from 'modelence/server'; await setConfig('voyage.apiKey', 'your_api_key_here'); ``` ## Step 7: Build the Frontend Create a React component to interact with your semantic search backend: ```tsx title="src/client/pages/VoyageSearchPage.tsx" theme={null} import { useState } from 'react'; import { useMutation, useQuery } from '@tanstack/react-query'; import { modelenceMutation, modelenceQuery } from 'modelence/client'; interface Document { _id: string; content: string; metadata: { title: string; description: string; }; createdAt: Date; } interface SearchResult extends Document { score: number; } export default function VoyageSearchPage() { const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [searchQuery, setSearchQuery] = useState(''); const [searchResults, setSearchResults] = useState([]); const { data: documents, refetch } = useQuery( modelenceQuery('voyage.getDocuments') ); const addDocument = useMutation(modelenceMutation('voyage.addDocument')); const deleteDocument = useMutation(modelenceMutation('voyage.deleteDocument')); const searchSimilar = useMutation(modelenceMutation('voyage.searchSimilar')); const handleAddDocument = async (e: React.FormEvent) => { e.preventDefault(); if (!title.trim() || !description.trim()) return; await addDocument.mutateAsync({ title, description }); setTitle(''); setDescription(''); refetch(); }; const handleSearch = async (e: React.FormEvent) => { e.preventDefault(); if (!searchQuery.trim()) return; const results = await searchSimilar.mutateAsync({ query: searchQuery }); setSearchResults(results as SearchResult[]); }; return (

Semantic Search with Voyage AI

{/* Search Form */}

Search Documents

setSearchQuery(e.target.value)} placeholder="Enter your search query..." className="flex-1 px-4 py-2 border rounded" />
{/* Search Results */} {searchResults.length > 0 && (

Found {searchResults.length} results

{searchResults.map((result) => (

{result.metadata.title}

{result.metadata.description}

Relevance: {(result.score * 100).toFixed(0)}%
))}
)}
{/* Add Document Form */}

Add New Document

setTitle(e.target.value)} placeholder="Document title..." className="w-full px-4 py-2 border rounded" />