Работа с InsForge и @insforge/sdk: БД, авторизация, хранилище, функции, платежи.

Звёзды47
Форки13
Авторinsforge
Обновлённоя 2 2026

Установка

SKILL.md

InsForge App Integration Skill

This skill covers client-side SDK integration using @insforge/sdk. For backend infrastructure operations (creating tables, inspecting schema, deploying functions, secrets, managing storage buckets, configuring payment provider keys/catalog, website deployments, cron job and schedules, logs, etc.), use the insforge-cli skill.

Quick Setup

1. Install the SDK

npm install @insforge/sdk@latest

2. Set up environment variables

Before using the SDK, create a .env file (or .env.local for Next.js) in your project root with your InsForge URL and anon key.

How to get your URL and anon key

  1. Ensure the project is linked. Check for .insforge/project.json in the project root.

    • Generate it with npx @insforge/cli link for an existing project or npx @insforge/cli create for a new project.
  2. Get the anon key via the CLI:

    npx @insforge/cli secrets get ANON_KEY
    
  3. Get the URL from the oss_host field in .insforge/project.json (e.g., https://myapp.us-east.insforge.app).

  4. Write both values to the .env file using the correct framework prefix (see table below).

Important: Use the anon key for user-scoped SDK clients, including SSR. For privileged server-only app code that needs admin/service access, use createAdminClient({ apiKey }); the API key is a full-access admin key, equivalent to a service role key on other platforms.

Use the correct environment variable prefix and access pattern for your framework:

Framework.env fileVariablesAccess Pattern
Next.js.env.localNEXT_PUBLIC_INSFORGE_URL, NEXT_PUBLIC_INSFORGE_ANON_KEYprocess.env.NEXT_PUBLIC_*
Vite (React, Vue, Svelte).envVITE_INSFORGE_URL, VITE_INSFORGE_ANON_KEYimport.meta.env.VITE_*
Astro.envPUBLIC_INSFORGE_URL, PUBLIC_INSFORGE_ANON_KEYimport.meta.env.PUBLIC_*
SvelteKit.envPUBLIC_INSFORGE_URL, PUBLIC_INSFORGE_ANON_KEYimport { env } from '$env/dynamic/public'
Create React App.envREACT_APP_INSFORGE_URL, REACT_APP_INSFORGE_ANON_KEYprocess.env.REACT_APP_*
Node.js / Server.envINSFORGE_URL, INSFORGE_ANON_KEYprocess.env.*

Example .env.local for Next.js:

NEXT_PUBLIC_INSFORGE_URL=https://your-appkey.us-east.insforge.app
NEXT_PUBLIC_INSFORGE_ANON_KEY=eyJhbGciOiJIUzI1NiIs...

Important: Keep .env files local. Add .env, .env.local, and .env*.local to your .gitignore and keep .env.example for documenting required variables.

3. Initialize the client

Next.js:

import { createClient } from '@insforge/sdk'

const insforge = createClient({
  baseUrl: process.env.NEXT_PUBLIC_INSFORGE_URL,
  anonKey: process.env.NEXT_PUBLIC_INSFORGE_ANON_KEY
})

Vite:

import { createClient } from '@insforge/sdk'

const insforge = createClient({
  baseUrl: import.meta.env.VITE_INSFORGE_URL,
  anonKey: import.meta.env.VITE_INSFORGE_ANON_KEY
})

Astro:

import { createClient } from '@insforge/sdk'

const insforge = createClient({
  baseUrl: import.meta.env.PUBLIC_INSFORGE_URL,
  anonKey: import.meta.env.PUBLIC_INSFORGE_ANON_KEY
})

For trusted server-only code that needs project-admin access:

import { createAdminClient } from "@insforge/sdk";

const admin = createAdminClient({
  baseUrl: process.env.INSFORGE_URL,
  apiKey: process.env.INSFORGE_API_KEY,
});

Module Reference

ModuleIntegration Guide
Databasedatabase/sdk-integration.md
Authauth/sdk-integration.md
Storagestorage/sdk-integration.md
Functionsfunctions/sdk-integration.md
AIai/overview.md
Real-timerealtime/sdk-integration.md
Emailemail/sdk-integration.md
Payments: Stripepayments/stripe.md
Payments: Razorpaypayments/razorpay.md

What Each Module Covers

ModuleContent
DatabaseCRUD operations, filters, pagination, RPC calls
AuthSign up/in, OAuth, sessions, profiles, password reset
StorageUpload, download, delete files; S3-compatible gateway for CI / backup tooling; write RLS policies for buckets
FunctionsInvoke edge functions
AIOpenRouter AI calls for chat, images, video, audio, embeddings, and model discovery
EmailSend custom transactional HTML emails (welcome, newsletter, notifications)
Payments: StripeStripe Checkout Sessions, subscriptions, and Billing Portal redirects
Payments: RazorpayRazorpay Orders, Subscriptions, Checkout.js, and subscription management
Real-timeConnect, subscribe, publish events, and track presence snapshots plus join/leave deltas

Guides

GuideWhen to Use
../insforge-cli/references/database/access-control.mdBackend setup for application-table access control — covers RLS, infinite recursion prevention, SECURITY DEFINER patterns, performance tips, and common InsForge patterns
storage/s3-gateway.mdFallback path when the consumer is existing S3 tooling (aws CLI, AWS SDKs, rclone, Terraform, boto3) and adopting @insforge/sdk is impractical — covers endpoint/region setup, access-key management, path-style addressing, and supported vs. not-supported S3 operations. Requires InsForge 2.0.9+. Prefer the SDK (storage/sdk-integration.md) for app code
storage/postgres-rls.mdWriting RLS policies for storage.objects — owner-only, public-read, path-scoped, team-shared, and the NULL uploaded_by caveat for mixed REST + S3 buckets
../insforge-cli/references/database/vector.mdBackend setup for semantic search, recommendations, or RAG — covers the vector extension, schema/dimensions, distance operators, HNSW/IVFFlat indexes, and RPC similarity search
ai/chat-completions.mdText generation, structured answers, and streaming chat through OpenRouter
ai/image-generation.mdImage generation/editing through OpenRouter, then durable storage in InsForge Storage
ai/video-generation.mdAsync OpenRouter video jobs, status polling, and storing generated media
ai/audio.mdSpeech-to-text, text-to-speech, and storing audio assets/transcripts with InsForge
ai/embeddings-and-rag.mdGenerating embeddings through OpenRouter, storing them in pgvector, and wiring up a basic RAG pipeline
ai/models-list.mdDiscovering OpenRouter model IDs, modalities, parameters, pricing, and embedding dimensions
paymentsConfiguring Stripe/Razorpay keys, syncing provider catalog, setting up webhooks, and writing payment RLS before app integration

Building Payments for a New App

First choose the provider. There is no generic app payments guide:

  • For Stripe Checkout, subscriptions, and Billing Portal, load payments/stripe.md.
  • For Razorpay Orders, Subscriptions, Checkout.js, and cancel/pause/resume flows, load payments/razorpay.md.

Before writing app code, check provider setup with the insforge-cli payments references:

npx @insforge/cli payments stripe status
npx @insforge/cli payments razorpay status

If the chosen provider is unconfigured, ask the developer/admin to configure that provider first.

Real-time Backend Setup

The real-time SDK is for frontend event handling and messaging. Configure channel patterns, database triggers, and channel/message RLS with the insforge-cli skill; see realtime.

Backend Configuration

Supported project config knobs are managed via the CLI — use npx @insforge/cli config export/plan/apply for auth redirect URLs, verification flags, password policy, auth SMTP settings, storage upload size, realtime/schedule retention, and cloud deployment subdomain. OAuth providers, external app setup, storage buckets, functions, secrets, and deployment env vars still use their dedicated dashboard or CLI flows. See the insforge-cli skill's Configuration section.

Risky backend changes? Use a branch first

When a code change in this skill depends on a schema migration, new RLS policy, OAuth provider config change, or any other backend change that affects prod behavior, create a backend branch first. Branches share JWT_SECRET (existing user JWTs keep working) but get a fresh database + EC2 + API_KEY / ANON_KEY, so you can test the SDK + backend change end-to-end in isolation.

The full branching workflow lives in the insforge-cli skill — see branch for the decision guide and lifecycle commands. Typical loop:

npx @insforge/cli branch create feat-x --mode schema-only
# ... apply migrations / change auth config / update RLS on the branch ...
# ... test the SDK against the branch backend ...
npx @insforge/cli branch merge feat-x --dry-run     # review SQL
npx @insforge/cli branch merge feat-x               # apply to parent

⚠ After branch create or branch switch, update the app's InsForge URL and anon-key env values, then restart your dev server (or re-source .env) so the SDK talks to the selected branch backend.

SDK Quick Reference

All SDK methods return { data, error }.

ModuleMethods
insforge.database.from().select(), .insert(), .update(), .delete(), .rpc()
insforge.auth.signUp(), .signInWithPassword(), .signInWithOAuth(), .signOut(), .getCurrentUser()
insforge.storage.from().upload(), .uploadAuto(), .download(), .remove()
insforge.functions.invoke()
insforge.aiDeprecated fallback only: .chat.completions.create(), .images.generate(), .embeddings.create()
insforge.realtime.connect(), .subscribe(), .publish(), .on(), .disconnect()
insforge.emails.send({ to, subject, html, cc?, bcc?, from?, replyTo? })
insforge.payments.stripe.createCheckoutSession(), .createCustomerPortalSession()
insforge.payments.razorpay.createOrder(), .verifyOrder(), .createSubscription(), .verifySubscription(), .cancelSubscription(), .pauseSubscription(), .resumeSubscription()

Important Notes

  • Database inserts require array format: insert([{...}])
  • Next.js / SSR auth: Use @insforge/sdk/ssr helpers (createBrowserClient, createServerClient, createAuthActions, createRefreshAuthRouter) and import updateSession from @insforge/sdk/ssr/middleware in Proxy/Middleware. Keep the refresh token httpOnly, run auth mutations through createAuthActions() on the server, return only safe app data from Server Actions, and let the browser read the short-lived access token for Storage/Realtime. See auth/ssr-integration.md
  • Storage: Save both url AND key to database for download/delete operations
  • Functions invoke URL: /functions/{slug}
  • Email delivery: Auth emails (signup verification, password reset, magic links, invites) ship on every plan. Custom email via insforge.emails.send() ships on every paid plan. Use the platform-managed delivery path; custom sender domain is dashboard config. See email/sdk-integration.md.
  • Payments: Configure provider keys/catalog with npx @insforge/cli payments <provider> ... first; frontend code uses provider-scoped SDK modules.
  • Payment RLS: Before payment UI, add app-specific RLS on provider runtime tables. Stripe uses payments.stripe_checkout_sessions and payments.stripe_customer_portal_sessions; Razorpay uses payments.razorpay_orders and payments.razorpay_subscriptions. Durable fulfillment triggers go on payments.webhook_events, not success URLs, Checkout callbacks, or payments.transactions.
  • Use Tailwind CSS v3.4
  • Always local build before deploy: Prevents wasted build resources and faster debugging
  • SDK package: Use @insforge/sdk directly for all features including authentication.
  • Deployment: Include a vercel.json in the project root for SPA routing (React, React Router apps). The download-template tool includes this automatically.
  • Branching for risky backend changes: If your SDK code depends on a new schema, RLS policy, or auth config change, create a branch via npx @insforge/cli branch create first — see the insforge-cli skill's branch reference. After branch create / branch switch, update the app's InsForge URL and anon-key env values, then restart the dev server.
  • Hit an InsForge-side hurdle? When the SDK, backend, docs, or a skill misbehaves — an API that should work but errors (--type bug), a capability you need that isn't supported (--type feature-request), docs that contradict actual behavior (--type bug --component docs with --doc/--expected) — report it and continue with a workaround: npx @insforge/cli feedback --json --type <bug|feature-request|friction> --component <backend|sdk|cli|skills|docs> --title "..." --detail "...", adding --language <lang> for SDK issues (no login required; PII is redacted locally). See the insforge-cli skill's Feedback section for the full flag set and situation→type mapping. Never file feedback for problems in the app code you are writing.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: insforge](https://darkplay.ru/ai/skills/agent-skills-insforge)

Похожие скиллы и другие разделы каталога

Похожие скиллы в категории «Интеграции»

Та же категория — сравните, что ещё подойдёт под вашу задачу.

mem0mem0ai · Справочник по Mem0 SDK: Python и TypeScript API, методы клиента, конфигурация и…
69 158 ★
opencli-usagejackwener · Обзор возможностей OpenCLI: адаптеры, флаги, форматы вывода и выбор нужного навыка.
31 150 ★
honcho-integrationplastic-labs · Интегрирует память и социальное познание Honcho в существующие кодовые базы на Python или…
8 176 ★
native-sdkvercel-labs · Обзорный навык для Native SDK — набора для создания нативных десктоп-приложений…
7 851 ★
cheat-initxbuilderlab · Рабочий процесс, превращающий каждый пост в калиброванный эксперимент: оценка, слепое…
7 593 ★
create-mcp-appmodelcontextprotocol · Руководство по созданию MCP Apps на MCP Apps SDK: UI, ресурсы, жизненный цикл.
3 114 ★
open-computer-useifuryst · Руководство по Open Computer Use — MCP-серверу и CLI для macOS, Linux и Windows.
3 016 ★
claude-to-imop7418 · Мост из сессии Claude Code или Codex в Telegram, Discord, Feishu/Lark, QQ или WeChat.
2 905 ★
feishu-bitablelarksuite · openclaw-lark — репозиторий навыков агента.
2 383 ★
figma-usefigma · Обязательный навык: загружайте перед каждым вызовом use_figma, иначе возможны…
2 205 ★
Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8