Vibe Coding Block (Classic apps)
Vibe Coding
The Vibe Coding Block lets you go beyond Softr’s standard blocks to build fully custom interfaces, all from a prompt. By isolating AI code generation to individual UI blocks, Vibe Coding acts as the ultimate extension layer and safety net. You get the limitless flexibility of “vibe coding” without the risk of breaking your app’s global security or core infrastructure. Connect it to your live data, add CRUD actions, and create personalized experiences to move beyond generated prototypes into bespoke production apps. Build and iterate confidently with version history built in, and make simple text and image edits directly without re-prompting.
What can you build?
Client dashboards, booking tools, progress trackers, calculators, notification feeds, partner portals, and more. Check out the videos below for examples.
Step-by-step: Using the Vibe Coding Block
1. Add the Vibe Coding Block and enter your prompt
Open your Softr app, click Add block, then select AI → Vibe Coding Block.
In the chat, describe what you want to build in plain English. The Vibe Coding Block supports both static and data-connected blocks. For example:
- A static layout like a page header, pricing table, or content section
- A dynamic, data-connected block like a dashboard, booking tool, or admin view that pulls from live data
You can also attach an image to your prompt (click the image icon in the bottom left of the chat box), which is useful for sharing a design reference or screenshot of what you’re going for.
Once you submit your prompt, Softr’s AI generates the interface inside the block. To connect a live data source, see Step 2.

2. Connect a data source (optional)
If you want your block to dynamically display live data, go to the Sources tab and connect a data source (Database + Table). You can also add conditional filters here.
The Vibe Coding Block supports Softr Databases and 15+ external data sources, including Airtable, Google Sheets, Notion, HubSpot, SQL, and more.

3. Add and configure CRUD and other actions (optional)
You can prompt the AI to add action buttons, such as:
- Create/add records
- Edit/update records
- Delete records
- Ask AI
After generating these functionalities in the UI, you can:
- Go to the Actions tab in the vibe coding block
- Review each action and configure permissions, conditions, or connected workflows as needed
For example, you could prompt: “Add a button that lets users submit a new booking request”. The AI will generate the UI and create a corresponding action you can configure in the Actions tab.
4. Control visibility and access
Use the Visibility tab to control which user groups can see the block. You can also set conditional filters in the Sources tab.

Managing version history
Each time you re-prompt the block, Softr saves a new version. This lets you experiment without losing earlier work.
Using Undo
For quick corrections, you can use the Undo button located directly in the AI chat on the last message. Clicking Undo instantly reverts the block to its immediate previous state.
Reverting and duplicating versions
To view or revert to any previous version:
- Open the Content tab
- Use the version dropdown at the top of the tab
- Select a previous version and click Restore to revert (or Duplicate as new to duplicate the block)

Editing text in the vibe-coded block
From the Content tab, go to Settings to edit text fields directly, for example, hero text, testimonials, or images. This option appears when the AI has generated editable text fields in your block.

Editing the generated code
If you want to make manual changes beyond what the AI generates, you can edit the underlying code yourself. Go to the Content tab → Code to see the full generated code. Make your changes and click Save to apply them.
You can use the AI chat for bigger structural changes and drop into the code for fine-tuned adjustments. Both approaches work together.
Copying the block to another project
To reuse a vibe-coded block in a different Softr project, hover over the block until the action icons appear on the right side. Click the Copy to icon and select the destination project. This is useful for replicating tools or UI patterns across client portals or apps.
Pricing and AI credits
The Vibe Coding Block uses AI credits. A certain number of monthly credits is available on each plan (including Free). Learn more about AI credits here.
Vibe Coding: Developer Guide
This guide is for developers who want to write code directly in the Vibe Coding Block, rather than prompting the AI. Use it when you need full control over your block’s markup, logic, and data.
The Basics
Block’s source code is a TypeScript file with a default-exported React component:
export default function Block() {
return (
<div className="container">
<div className="content">
<h1 className="text-4xl font-extrabold tracking-tight text-balance">
Hello, world!
</h1>
</div>
</div>
);
}This only runs in the browser - you can fetch and mutate data from connected data sources, but you cannot run server-side code or use Node.js APIs.
Vibe coding block is configured to use Tailwind for styling and shadcn/ui for components, but you are free to import any public npm package as needed. In fact, any npm package import you add will automatically install it for you.
import { format } from "date-fns"; // will be resolved at compile time
export default function Block() {
const today = format(new Date(), "MMMM d, yyyy");
return <div>Today's date is {today}</div>;
}shadcn/ui
shadcn/ui components are already pre-configured and follow your app’s theme out of the box. They’re available under the @/components/ui path, so you can import them like this:
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";Currently the following components are available:
accordion, alert, alert-dialog, aspect-ratio, avatar, badge, button, calendar, card, carousel, chart, checkbox, collapsible, command, context-menu, dialog, drawer, dropdown-menu, empty, hover-card, input, input-group, input-otp, item, kbd, label, menubar, native-select, navigation-menu, pagination, popover, progress, radio-group, resizable, scroll-area, select, separator, sheet, skeleton, slider, sonner, spinner, switch, table, tabs, textarea, toggle, toggle-group, tooltip
Check out the shadcn/ui docs for usage details and examples for each component.
Icons
Preferred icon pack is Lucide Icons, but you can opt for a different one.
import { TrendingUp, User, Settings } from "lucide-react";Styling
We follow the default shadcn/ui naming convention for background/foreground color pairs (e.g. bg-primary / text-primary-foreground) which maps to your app’s theme colors.
By default, a block occupies full width of the page but special classes - container and content are available to constrain the width of content to match app’s max width settings to ensure visual consistency with other blocks:
<div className="container">
<div className="content">
{/* your content here */}
</div>
</div>Data from Your Datasource
Import data hooks from @/lib/datasource. Use these when you want to display records from your connected data source. All data fetching hooks follow a query builder pattern so you can be quite expressive with your queries.
One or many datasources
A block can connect to multiple datasources. When it does, every fetch or mutation needs to say which datasource it targets. The datasource.define utility gives you readable aliases for that. Declare it once at the top of the file, then pass the alias as from on each hook:
import { datasource, useRecords, q } from "@/lib/datasource";
const ds = datasource.define({
orders: "ds_id_1",
customers: "ds_id_2",
});
const ordersSelect = q.select({ product: "field1", total: "field2" });
const customersSelect = q.select({ name: "field3", email: "field4" });
export default function Block() {
const { data: orders } = useRecords({ from: ds.orders, select: ordersSelect });
const { data: customers } = useRecords({ from: ds.customers, select: customersSelect });
// ...
}With a single datasource you can skip datasource.define and omit from. The hooks then default to that one datasource. As soon as a block has more than one, leaving out from throws an error, since the hook can’t tell which datasource the call belongs to.
Every record hook takes from the same way: useRecords, useRecord, useLinkedRecords, useFieldOptions, useMetric, useChartData, useRecordCreate, useRecordUpdate, and useRecordDelete. useUpload and useCurrentRecordId work at the app level and thus from is not applicable to them.
Defining a select query
Field mappings have to be static, we also use static analysis to determine which fields your block actually uses so we don’t overfetch and don’t accidentally expose potentially sensitive data.
import { q } from "@/lib/datasource";
const select = q.select({
title: "FIELD_ID1", // key = alias used in code, value = actual field ID
description: "FIELD_ID2",
createdAt: "FIELD_ID3",
});So something like this is not allowed as it breaks static analysis:
const select = q.select({
[dynamicKey]: "FIELD_ID1", // ❌ dynamic keys not allowed
title: getFieldId(), // ❌ dynamic values not allowed
});useRecords: fetch a list of records
import { useRecords, q } from "@/lib/datasource";
export default function Block() {
const {
data, // array of pages with shape { items: Record[]; total: number; offset: string | number | null }
status, // "pending" | "success" | "error"
error, // Error object if status is "error"
fetchNextPage, // function to fetch the next page of results
hasNextPage, // boolean indicating if there are more pages to fetch
isFetching, // boolean indicating if any page is currently being fetched
isFetchingNextPage, // boolean indicating if the next page is currently being fetched
refetch, // function to refetch the data (e.g. after a mutation)
isRefetching, // boolean indicating if a refetch is currently in progress
isRefetchError, // boolean indicating if the last refetch resulted in an error
} = useRecords({
select: q.select({
name: "FIELD_ID1",
email: "FIELD_ID2",
}),
count: 6, // records per page, default 6, max 100
// from: ds.orders, // datasource alias, required when the block has multiple datasources
// where: ..., // optional filter
// orderBy: ..., // optional sort
// enabled: ..., // optional boolean to defer loading (e.g. until component is visible)
});
if (status === "pending") return <div>Loading...</div>;
if (status === "error") return <div>Error loading data</div>;
const items = data.pages.flatMap(page => page.items);
return (
<div className="container py-8">
<div className="content space-y-4">
{items.map((item) => (
<div key={item.id}>
<p className="font-semibold">{item.fields.name}</p>
<p className="text-muted-foreground">{item.fields.email}</p>
</div>
))}
{hasNextPage && (
<button onClick={() => fetchNextPage()} disabled={isFetching}>
{isFetchingNextPage ? "Loading..." : "Load More"}
</button>
)}
</div>
</div>
);
}useRecord: fetch a single record by ID
Use with useCurrentRecordId() to display details of the record currently shown in a list/detail context:
import { useRecord, useCurrentRecordId, q } from "@/lib/datasource";
export default function Block() {
const recordId = useCurrentRecordId(); // resolves the ID of the current record from page, can also be null
const { data, status } = useRecord({
select: q.select({
title: "FIELD_ID1",
description: "FIELD_ID2",
}),
recordId,
// from: ds.orders, // datasource alias, required when the block has multiple datasources
});
if (status === "pending") return <div>Loading...</div>;
if (status === "error") return <div>Error</div>;
if (!data) return <div>Not found</div>;
return (
<div className="container py-8">
<div className="content">
<h1>{data.fields.title}</h1>
<p>{data.fields.description}</p>
</div>
</div>
);
}Filtering records
Use the q query builder for filters. Filters support up to 2 levels of nesting.
useRecords({
select,
where: q.and(
q.text("name").contains("Alice"),
q.number("age").gte(18),
q.or(
q.boolean("isActive").is(true),
q.text("notes").isNotEmpty()
)
),
});Available filter methods:
| Builder | Methods |
|---|---|
q.text(field) | is, isNot, contains, startsWith, endsWith, isOneOf, isNoneOf, hasAllOf, isEmpty, isNotEmpty |
q.number(field) | is, isNot, gt, gte, lt, lte, between, isEmpty, isNotEmpty |
q.boolean(field) | is, isNot, isEmpty, isNotEmpty |
q.date(field) | is, isNot, gt, gte, lt, lte, between, isNotBetween, isEmpty, isNotEmpty |
q.array(field) | is, isOneOf, isNoneOf, hasAllOf, isEmpty, isNotEmpty |
q.and(...) | combine filters with AND |
q.or(...) | combine filters with OR |
Sorting records
useRecords({
select,
orderBy: q.desc("createdAt"), // or q.asc("createdAt")
});
// Multiple sort fields (tie-breakers):
useRecords({
select,
orderBy: [q.asc("lastName"), q.asc("firstName")],
});useLinkedRecords: fetch options from a linked table
Use for dropdowns, comboboxes, or tag pickers where you need to show values from a related table:
import { q, useLinkedRecords } from "@/lib/datasource";
export default function Block() {
const {
data,
status,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
refetch,
isRefetching,
isRefetchError,
} = useLinkedRecords({
select: q.select({ category: "$CATEGORY_FIELD_ID" }),
field: "category", // alias from select that holds the linked field
sortOrder: "ASC", // "ASC" | "DESC"
search: "", // optional search term
enabled: true, // set false to defer loading (e.g. until dropdown opens)
// from: ds.orders, // datasource alias, required when the block has multiple datasources
// count: ..., // optional page size, defaults to 100, max 1000
});
const options = data?.pages.flatMap(p => p.items) ?? [];
return (
<div>
{options.map(opt => (
<span key={opt.id}>{opt.title}</span>
))}
</div>
);
}Each item only carries its id and title (the linked table’s primary field). To read other fields off those records, connect the linked table as its own datasource and query it with useRecords. See One or many datasources.
Mutating Records
All mutation hooks expose an enabled boolean. Always check it before rendering the mutation UI or calling the function. It reflects whether the current user has sufficient permissions. If called without checking enabled, the mutation will throw an error.
useRecordCreate
import { useRecordCreate, q } from "@/lib/datasource";
import { toast } from "sonner";
export default function Block() {
const {
enabled, // boolean indicating if the user has permission to create records
mutate, // void function to create a record, accepts an object with shape from provided fields, in this case - `{ name: string; email: string }`
mutateAsync, // async version of mutate that returns a promise with the created record
status, // "idle" | "pending" | "success" | "error"
error, // Error object if status is "error"
reset, // function to reset the status and error state back to "idle" and null, useful for showing multiple create forms in a row
} = useRecordCreate({
fields: q.select({
name: "FIELD_ID1",
email: "FIELD_ID2",
}),
onSuccess: (newRecord) => toast.success("Created!"),
onError: (error) => toast.error(error.message),
// from: ds.orders, // datasource alias, required when the block has multiple datasources
});
return (
<div>
{enabled && (
<button
onClick={() => mutate({ name: "Jane", email: "jane@example.com" })}
disabled={status === "pending"}
>
{status === "pending" ? "Saving..." : "Add Record"}
</button>
)}
</div>
);
}useRecordUpdate
import { useRecordUpdate, q } from "@/lib/datasource";
export default function Block() {
const { data, refetch } = useRecords({ ... });
const {
enabled,
mutate,
mutateAsync,
status,
error,
reset,
} = useRecordUpdate({
fields: q.select({ status: "FIELD_ID1" }),
onSuccess: async (updatedRecord) => {
// refetch the data first to ensure the UI shows the latest value before notifying the user.
await refetch();
toast.success("Updated!");
},
onError: (error) => toast.error(error.message),
// from: ds.orders, // datasource alias, required when the block has multiple datasources
});
const onUpdateClick = () => {
if (!enabled) return;
mutate({
recordId: "RECORD_ID", // ID of the record to update
fields: { status: "active" }, // updated field values
});
};
}useRecordDelete
import { useRecordDelete } from "@/lib/datasource";
export default function Block() {
const {
enabled,
mutate,
mutateAsync,
status,
error,
reset,
} = useRecordDelete({
onSuccess: async ({ recordId }) => {
await refetch();
toast.success("Deleted!");
},
onError: (error) => toast.error(error.message),
// from: ds.orders, // datasource alias, required when the block has multiple datasources
});
const onDeleteClick = () => {
if (!enabled) return;
mutate("RECORD_ID"); // ID of the record to delete
};
}Phone fields
When writing to a PHONE field, the value must be in unformatted international format: + followed by digits only (e.g. +12125550100). Some datasources (such as Monday.com) reject values that contain spaces, dashes, or parentheses. Strip all non-digit characters except the leading + before submitting:
const sanitizePhone = (raw: string) => raw.replace(/[^\d+]/g, "").replace(/(?!^)\+/g, "");
mutate({ phone: sanitizePhone(inputValue) });Uploading Files
Use useUpload from @/lib/datasource to upload files and get back a URL to store in a record.
import { useUpload, useRecordCreate, q } from "@/lib/datasource";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { useState } from "react";
const fields = q.select({
name: "$NAME_FIELD_ID",
attachment: "$ATTACHMENT_FIELD_ID",
});
export default function Block() {
const [name, setName] = useState("");
const [file, setFile] = useState<File | null>(null);
const { uploadAsync, isUploading } = useUpload();
const createRecord = useRecordCreate({
fields,
onSuccess: () => toast.success("Submitted!"),
});
const handleSubmit = async () => {
if (!file) return;
const [result] = await uploadAsync(file);
if (result.status === "completed") {
createRecord.mutate({
name,
attachment: { filename: result.file.name, url: result.url },
});
} else {
toast.error(result.error?.message ?? "Upload failed");
}
};
return (
<div className="container py-6">
<div className="content space-y-4 max-w-md">
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />
<Input type="file" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
<Button onClick={handleSubmit} disabled={isUploading || !file}>
{isUploading ? "Uploading..." : "Submit"}
</Button>
</div>
</div>
);
}For multiple files:
const results = await uploadAsync(Array.from(e.target.files));
const completed = results.filter(r => r.status === "completed");Current User
Get info about the logged-in user with useCurrentUser from @/lib/user. Returns null if no user is logged in.
import { useCurrentUser } from "@/lib/user";
export default function Block() {
const user = useCurrentUser();
if (!user) return <div>Please log in to continue.</div>;
return (
<div className="container py-8">
<div className="content flex items-center gap-4">
{user.avatar && (
<img src={user.avatar} alt={user.fullName ?? ""} className="w-10 h-10 rounded-full" />
)}
<div>
<p className="font-semibold">{user.fullName}</p>
<p className="text-muted-foreground text-sm">{user.email}</p>
</div>
</div>
</div>
);
}Available fields:
id:string | null(only present when user sync is enabled)fullName:string | nullfirstName:string | nulllastName:string | nullemail:string | nullavatar:string | null
Custom user properties
Beyond the reserved fields above, any custom fields that exist on your user record are available under user.properties. Pass a properties map to alias each field to a readable name, the same way a select query works.
import { useCurrentUser } from "@/lib/user";
export default function Block() {
const user = useCurrentUser({
properties: {
stripeId: "FIELD_ID1",
plan: "FIELD_ID2",
},
});
if (!user) return <div>Please log in to continue.</div>;
return (
<div className="container py-8">
<div className="content">
<p className="font-semibold">Welcome, {user.fullName}!</p>
{user.properties.stripeId && <p className="text-muted-foreground text-sm">Stripe ID: {user.properties.stripeId}</p>}
{user.properties.plan && <p className="text-muted-foreground text-sm">Your plan: {user.properties.plan}</p>}
</div>
</div>
);
}Metrics & Charts
useMetric: single aggregated value
Useful for KPI cards (total sales, average rating, etc.):
import { useMetric, q, metric } from "@/lib/datasource";
export default function Block() {
const { data, status } = useMetric({
select: q.select({ revenue: "$REVENUE_FIELD_ID" }),
metric: metric.sum("revenue"),
// from: ds.orders, // datasource alias, required when the block has multiple datasources
// where: q.date("createdAt").gte("2025-01-01"),
});
if (status === "pending") return <div>Loading...</div>;
return <div className="text-4xl font-bold">${data?.toFixed(2)}</div>;
}Aggregations: metric.sum(field), metric.avg(field), metric.max(field), metric.min(field), metric.distinct(field), metric.count()
useChartData: grouped data for charts
import { useChartData, q, metric } from "@/lib/datasource";
import { LineChart, Line, XAxis, CartesianGrid } from "recharts";
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart";
const chartConfig = {
revenue: { label: "Revenue", color: "var(--chart-1)" },
} satisfies ChartConfig;
export default function Block() {
const { data, status } = useChartData({
select: q.select({
date: "$DATE_FIELD_ID",
revenue: "$REVENUE_FIELD_ID",
}),
orderBy: q.asc("date"),
metric: { revenue: metric.sum("revenue") },
groupBy: metric.groupBy("date", metric.bucket.month.long),
// from: ds.orders, // datasource alias, required when the block has multiple datasources
});
if (status === "pending") return <div>Loading...</div>;
return (
<div className="container py-8">
<div className="content">
<ChartContainer config={chartConfig}>
<LineChart data={data} margin={{ left: 12, right: 12 }}>
<CartesianGrid vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} tickMargin={8} />
<ChartTooltip content={<ChartTooltipContent />} />
<Line dataKey="revenue" stroke="var(--color-revenue)" strokeWidth={2} dot={false} />
</LineChart>
</ChartContainer>
</div>
</div>
);
}Grouping buckets:
| Bucket | Format example |
|---|---|
metric.bucket.year | 2025 |
metric.bucket.month.iso | "2025-03" |
metric.bucket.month.long | "March 2025" |
metric.bucket.day.iso | "2025-03-15" |
metric.bucket.day.long | "Mar 15, 2025" |
Comments
Comments live on records. They’re set up once for the whole app in Settings → Comments. The hooks in @/lib/comments give you one thread per record: you lay it out, the app owns the data, the copy and the permissions.
Don’t build your own thread on top of a datasource field. Comments written that way are invisible to every other block in the app, and to the builder’s moderation tools.
useCommentsSettings
Every label, placeholder, empty-state message and the sort direction comes from here. A builder edits them in Settings → Comments and expects the change to show up right away, with no republish. So read them from the hook. Don’t hardcode strings.
Don’t expose them as useTextSetting either. That’s a second source of truth, and it quietly overrides the app’s settings.
function useCommentsSettings(options: {
/** Which layout you're building. The two layouts have separate display settings. */
displayAs: "BLOCK" | "SIDE_PANEL";
/** Which datasource the thread is on. Required on a multi-datasource block. */
from?: string;
}): {
commentListTitle: string; // may be empty; render no heading rather than an empty one
commentBoxPlaceholder: string;
submitButtonLabel: string;
deleteButtonLabel: string;
loadMoreCommentsButtonLabel: string;
emptyStateMessage: string; // shown instead of the list when the thread is empty
notificationsToggleLabel: string;
sortDirection: "NEWEST_ON_TOP" | "OLDEST_ON_TOP";
surface: boolean; // whether each comment sits on its own card
showVerticalLine: boolean; // whether a line joins consecutive comments into one thread
commentPanelDisplayMode: "PUSH_MAIN_CONTENT" | "COVER_MAIN_CONTENT"; // SIDE_PANEL only
canPost: boolean; // false for a viewer who can read the thread but not post
quickReactions: Array<{ emoji: string; label: string }>; // the only emoji this surface can post
allowMentions: boolean; // false when the app has mentions turned off
} | nulldisplayAs picks which settings you get. Settings → Comments has two separate sets of display options, one per layout. Pass "BLOCK" for a thread in the block’s own flow, "SIDE_PANEL" for a docked panel. Pass the wrong one and the builder’s edits look like they do nothing.
Keep the field names when you destructure. commentListTitle is the “Comment list title” setting, submitButtonLabel is “Submit button label”. Rename it to title and the link to the control the builder edits is gone.
null means render no comments UI at all. You get it when the app has no comment settings, when that table isn’t registered for comments, or when the viewer can’t see the thread. It’s not an error, and it’s not a reason to fall back to something of your own.
import { useCommentsSettings } from "@/lib/comments";
export default function Block() {
const settings = useCommentsSettings({ displayAs: "BLOCK" });
if (!settings) return null;
return (
<section>
{settings.commentListTitle && <h2>{settings.commentListTitle}</h2>}
{settings.canPost && (
<form>
<textarea placeholder={settings.commentBoxPlaceholder} />
<button type="submit">{settings.submitButtonLabel}</button>
</form>
)}
</section>
);
}The rest of @/lib/comments builds the thread itself: useComments, useCommentCreate, useCommentDelete, useCommentReactions, useCommentComposer, useMentionSuggestions and useCommentSubscription.
Editable Settings
Editable settings let builders modify block content through the editor UI (Content → Settings tab) without touching code. Always use them for any text, images, icons, colors, or lists that might change between block instances.
Import from @/lib/editable-settings.
useTextSetting
Returns a string. Use for titles, descriptions, button labels, URLs, etc.
import { useTextSetting } from "@/lib/editable-settings";
export default function Block() {
const title = useTextSetting({
name: "title", // unique identifier; changing this resets the value
label: "Title", // shown in the editor UI
initialValue: "Welcome", // starting value
required: false, // optional, default false
});
return <h1>{title}</h1>;
}useImageSetting
Returns { src: string; alt: string }.
import { useImageSetting } from "@/lib/editable-settings";
export default function Block() {
const image = useImageSetting({
name: "hero-image",
label: "Hero Image",
initialValue: {
src: "https://images.unsplash.com/photo-...",
alt: "A hero image",
},
});
return <img src={image.src} alt={image.alt} className="w-full rounded-lg" />;
}useVideoSetting
Returns { src: string }.
import { useVideoSetting } from "@/lib/editable-settings";
export default function Block() {
const video = useVideoSetting({
name: "intro-video",
label: "Intro Video",
initialValue: { src: "https://example.com/video.mp4" },
});
return <video src={video.src} controls className="w-full" />;
}useVibeCodingBlockIconSetting
Returns { icon: string } where icon is a lucide-react icon name. Render it with the DynamicIcon component.
import { useVibeCodingBlockIconSetting } from "@/lib/editable-settings";
import { DynamicIcon } from "@/components/dynamic-icon";
export default function Block() {
const { icon } = useVibeCodingBlockIconSetting({
name: "feature-icon",
label: "Feature Icon",
initialValue: { icon: "trending-up" },
});
return <DynamicIcon name={icon} className="w-6 h-6" />;
}useNavigationSetting
Returns one of:
{
action: "OPEN_URL" | "OPEN_PAGE";
destination: string;
openIn: "SELF" | "TAB" | "MODAL";
modalSize: "SM" | "MD" | "LG" | "XL"; // only used when openIn is "MODAL"
modalType: "POPUP" | "SLIDING"; // only used when openIn is "MODAL"
}
| { action: "OPEN_CHAT"; actionId: string | undefined }
| { action: "TRIGGER_CUSTOM_WORKFLOW"; actionId: string | undefined }The builder picks the action and how it opens. Your code just passes the value to NavigationAction or navigate().
initialValue sets the starting point, and takes a looser shape than what you get back:
- Link:
{ destination, action?, openIn?, modalSize?, modalType? }.actioncomes fromdestination: a destination that starts with/meansOPEN_PAGE, anything elseOPEN_URL.openIndefaults toTAB. - Chat or workflow:
{ action: "OPEN_CHAT" }or{ action: "TRIGGER_CUSTOM_WORKFLOW" }. The builder picks which action it points at, so there’s nothing else to set.
import { NavigationAction } from "@/components/navigation-action";
import { Button } from "@/components/ui/button";
import { useNavigationSetting } from "@/lib/editable-settings";
export default function Block() {
const navigation = useNavigationSetting({
name: "cta-navigation",
label: "CTA Navigation",
initialValue: {
action: "OPEN_PAGE",
destination: "/pricing",
openIn: "TAB",
},
});
return (
<Button asChild>
<NavigationAction navigation={navigation}>
Click me!
</NavigationAction>
</Button>
);
}The NavigationAction component also accepts optional recordId?: string and datasourceId?: string props. When rendering record-specific links/actions, pass both the current record ID and the datasource it belongs to. datasourceId is required whenever recordId is present. It tells the runtime which datasource the selected record comes from. Also, in the case of a link, it dynamically adds a URL parameter to the final URL ?recordId=<id>.
<NavigationAction navigation={detailsLink} recordId={item.id} datasourceId="d347bd84-7dc5-4d19-bc98-68417c6ae147">
View details
</NavigationAction>useNavigation
Some things aren’t links: a chart segment, a table row, a countdown, a form that just submitted. For those, call navigate() from useNavigation. It takes the same setting NavigationAction takes and opens it the same way, so the builder’s choice still applies.
Call it once per block. The setting is an argument, so one navigate handles every destination.
import { useNavigation, useNavigationSetting } from "@/lib/editable-settings";
import { useRecordCreate, q } from "@/lib/datasource";
import { Button } from "@/components/ui/button";
export default function Block() {
const navigate = useNavigation();
const afterSubmit = useNavigationSetting({
name: "after-submit",
label: "After Submit",
initialValue: { destination: "/thank-you", openIn: "SELF" },
});
const createRecord = useRecordCreate({
fields: q.select({ name: "FIELD_ID1" }),
onSuccess: () => navigate(afterSubmit),
});
return <Button onClick={() => createRecord.mutate({ name: "New user" })}>Submit</Button>;
}The second argument takes the same recordId and datasourceId as NavigationAction, for a destination that points at one record:
<BarChart
onBarClick={(bar) =>
navigate(detailsLink, { recordId: bar.id, datasourceId: "d347bd84-7dc5-4d19-bc98-68417c6ae147" })
}
/>What navigate() does, per setting:
| Setting | What happens |
|---|---|
OPEN_PAGE / OPEN_URL, openIn: "SELF" | Navigates the app there |
OPEN_PAGE / OPEN_URL, openIn: "TAB" | Opens in a new tab |
OPEN_PAGE / OPEN_URL, openIn: "MODAL" | Opens in a modal, with the builder’s modalSize and modalType |
OPEN_CHAT | Opens the AI chat for that action |
TRIGGER_CUSTOM_WORKFLOW | Runs the workflow with recordId and datasourceId |
recordId gets added to page and URL destinations as ?recordId=<id>. It’s skipped for #section, mailto:, tel: and sms: destinations, because there is nowhere to put it.
If the setting points at an action the builder deleted or hid, navigate() does nothing. No error, no toast, so don’t bother guarding the call.
Use NavigationAction whenever a real link will do. An anchor gives you middle-click, “open in new tab” and the browser’s hover preview. A click handler loses all three. And don’t fall back to window.open or window.location. Those hardcode the destination, so the builder can’t change it anymore.
useColorSetting
Returns a CSS color string. Use for a color the builder picks: title color, button background, etc. It shows up as a color picker in the Content tab.
initialValue is a theme color name or a hex ("#1A2B3C"). Default is "foreground". Theme names:
background, foreground, card, card-foreground, popover, popover-foreground, primary, primary-foreground, secondary, secondary-foreground, muted, muted-foreground, accent, accent-foreground, destructive, border, input, ring
import { useColorSetting, useTextSetting } from "@/lib/editable-settings";
export default function Block() {
const title = useTextSetting({ name: "title", label: "Title", initialValue: "Welcome" });
const titleColor = useColorSetting({
name: "title-color",
label: "Title Color",
initialValue: "foreground",
});
return (
<h1 className="text-2xl font-semibold" style={{ color: titleColor }}>
{title}
</h1>
);
}A theme name follows the app theme until the builder picks a color. The picker shows the current theme color, and once the builder changes it, a hex is saved.
Pass the value through inline style, not a Tailwind class. Classes like text-[...] are built at compile time and won’t pick up the builder’s color.
Pick the initialValue that matches the element’s current look, so nothing changes until the builder edits it: text-foreground → "foreground", bg-primary → "primary".
useArraySetting
Returns an array of items with a consistent shape. Use for feature lists, team members, FAQs, testimonials, etc.
import { useArraySetting } from "@/lib/editable-settings";
import { DynamicIcon } from "@/components/dynamic-icon";
export default function Block() {
const features = useArraySetting({
name: "features",
label: "Features",
schema: {
title: { type: "text", label: "Title", initialValue: "Feature" },
description: { type: "text", label: "Description" },
icon: { type: "vibeCodingBlockIcon", label: "Icon" },
image: { type: "image", label: "Image" },
},
initialValue: [
{
title: "Fast",
description: "Blazing fast performance.",
icon: { icon: "zap" },
image: { src: "", alt: "" },
},
{
title: "Reliable",
description: "99.9% uptime guaranteed.",
icon: { icon: "shield" },
image: { src: "", alt: "" },
},
],
});
return (
<div className="container py-12">
<div className="content grid md:grid-cols-2 gap-6">
{features.map((feature, index) => (
<div key={index} className="flex gap-4">
<DynamicIcon name={feature.icon.icon} className="w-6 h-6 text-primary" />
<div>
<h3 className="font-semibold">{feature.title}</h3>
<p className="text-muted-foreground text-sm">{feature.description}</p>
</div>
</div>
))}
</div>
</div>
);
}useBooleanSetting
Returns a boolean. Use for toggles, switches, show/hide elements, etc.
import { useBooleanSetting } from "@/lib/editable-settings";
export default function Block() {
const showHeader = useBooleanSetting({
name: "toggleHeader", // unique identifier; changing this resets the value
label: "Toggle header", // shown in the editor UI
initialValue: false, // starting value (default is true)
});
return <>{showHeader && <Header />}</>;
}Schema field types: "text", "image", "video", "vibeCodingBlockIcon", "color"
A "color" field comes back as a CSS color, same as useColorSetting.
Constraints:
- Schema cannot contain nested arrays. For list-like text, use a
"text"field with a separator (e.g. comma) and split it in code - Do not put a
vibeCodingBlockIconfield as the first field in the schema - Calling two settings hooks with the same
nameis not allowed
Complete Example: Feature Showcase
A full-featured block combining editable settings, datasource records, and shadcn/ui:
import { useTextSetting, useArraySetting } from "@/lib/editable-settings";
import { useRecords, q } from "@/lib/datasource";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { DynamicIcon } from "@/components/dynamic-icon";
const select = q.select({
name: "$PRODUCT_NAME_FIELD",
category: "$CATEGORY_FIELD",
price: "$PRICE_FIELD",
});
export default function Block() {
// Editable settings for the section header
const heading = useTextSetting({
name: "heading",
label: "Section heading",
initialValue: "Our Products",
});
const subheading = useTextSetting({
name: "subheading",
label: "Section subheading",
initialValue: "Explore our latest offerings",
});
// Live records from datasource
const { data, status, hasNextPage, fetchNextPage, isFetching } = useRecords({
select,
count: 6,
orderBy: q.asc("name"),
});
const items = data?.pages.flatMap(p => p.items) ?? [];
return (
<div className="container py-12">
<div className="content">
<div className="text-center mb-10">
<h2 className="text-3xl font-heading font-bold">{heading}</h2>
<p className="text-muted-foreground mt-2">{subheading}</p>
</div>
{status === "pending" && (
<div className="flex justify-center py-12">
<div className="text-muted-foreground">Loading...</div>
</div>
)}
{status === "error" && (
<div className="text-destructive text-center">Failed to load products.</div>
)}
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
{items.map((item) => (
<Card key={item.id}>
<CardHeader>
<Badge variant="secondary" className="w-fit">
{item.fields.category?.label ?? "Uncategorized"}
</Badge>
<CardTitle className="mt-2">{item.fields.name}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-2xl font-bold">
${(item.fields.price as number)?.toFixed(2)}
</p>
</CardContent>
</Card>
))}
</div>
{hasNextPage && (
<div className="flex justify-center mt-8">
<button
onClick={() => fetchNextPage()}
disabled={isFetching}
className="text-primary underline underline-offset-4 hover:no-underline"
>
{isFetching ? "Loading..." : "Load more"}
</button>
</div>
)}
</div>
</div>
);
}Fetching field options
Use useFieldOptions to fetch available options for SELECT or multi-select fields. This is useful for building filters, dropdowns, badges, or any UI that needs to display the available choices from the datasource without hardcoding them. Like the other data hooks, it accepts a from alias (useFieldOptions({ from: ds.orders, select, field })), required when the block has multiple datasources.
Example to build a filter UI using useFieldOptions:
import { useState } from "react";
import { q, useRecords, useFieldOptions } from "@/lib/datasource";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const select = q.select({
title: "$TITLE_FIELD_ID",
productStatus: "$PRODUCT_STATUS_FIELD_ID",
});
export default function Block() {
const [selectedProductStatus, setSelectedProductStatus] = useState<string | null>(null);
const { options } = useFieldOptions({ select, field: "productStatus" });
const { data, status } = useRecords({
select,
where: selectedProductStatus ? q.text("productStatus").is(selectedProductStatus) : undefined,
count: 10,
});
const items = data?.pages.flatMap((p) => p.items) ?? [];
return (
<div className="container py-6">
<div className="content space-y-4">
<Select
value={selectedProductStatus ?? "all"}
onValueChange={(val) => setSelectedProductStatus(val === "all" ? null : val)}
>
<SelectTrigger className="w-48">
<SelectValue placeholder="Filter by product status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Product Statuses</SelectItem>
{options.map((opt) => (
<SelectItem key={opt.id} value={opt.id}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
{status === "pending" && <div>Loading...</div>}
{items.map((item) => (
<div key={item.id}>
<div>{item.fields.title}</div>
<div>{item.fields.productStatus?.label || "Unknown"}</div>
</div>
))}
</div>
</div>
);
}Fetching from a REST API
When using a REST API as a datasource, call it with useProxyFetch from @/lib/datasource. The proxy attaches authentication for you, so don’t send tokens, API keys, or auth headers yourself.
useProxyFetch returns a function with the same signature as fetch. TanStack Query (or a similar data-fetching library) pairs nicely with it for caching and request state, and we strongly recommend it over fetching inside a useEffect.
Reading data
import { useQuery } from "@tanstack/react-query";
import { useProxyFetch } from "@/lib/datasource";
export default function Block() {
const proxyFetch = useProxyFetch();
const { data, status, error } = useQuery({
queryKey: ["products"],
queryFn: async () => {
const res = await proxyFetch("https://api.example.com/products");
if (!res.ok) throw new Error("Failed to fetch products");
return res.json();
},
});
if (status === "pending") return <div>Loading...</div>;
if (status === "error") return <div>{error.message}</div>;
return (
<div className="container py-6">
<div className="content space-y-2">
{data.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
</div>
);
}Mutating data
Wrap writes in useMutation and invalidate the affected queries on success so the UI refetches:
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useProxyFetch } from "@/lib/datasource";
import { toast } from "sonner";
function useCreateProduct() {
const proxyFetch = useProxyFetch();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { name: string; price: number }) => {
const res = await proxyFetch("https://api.example.com/products", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) throw new Error("Failed to create product");
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["products"] });
toast.success("Created");
},
});
}Multiple datasources
When a block has more than one datasource, useProxyFetch needs to know which one to route the request to, so pass the datasource alias as its argument. With a single datasource you can call useProxyFetch() with no argument; once there’s more than one, leaving it out throws an error. Define the aliases with datasource.define, the same pattern the record hooks use:
import { useQuery } from "@tanstack/react-query";
import { datasource, useProxyFetch } from "@/lib/datasource";
const ds = datasource.define({
store: "ds_id_1",
});
function useProducts() {
const proxyFetch = useProxyFetch(ds.store);
return useQuery({
queryKey: ["products"],
queryFn: async () => {
const res = await proxyFetch("https://api.example.com/products");
if (!res.ok) throw new Error("Failed to fetch products");
return res.json();
},
});
}Vibe coding blocks
Vibe coding blocks are custom React components you add to a page when the built-in blocks don’t do what you need. These tools let an assistant write and maintain them from outside Softr Studio, so you can ask for a block in the same conversation where you explored the data it should show.
The framework reference is in the Vibe Coding Developer Guide. The assistant reads the current version of it with vibe_coding_block_get_docs before writing code.
Good to know
A broken block can’t be saved. Code is checked before it is stored, so if something is wrong the block keeps working as it did and nothing is lost.
A version is a snapshot of the whole block. One is saved each time the code changes, capturing the block as it stands at that moment: its code, but also its settings, visibility, and connected data sources. Changing only a setting doesn’t create a version of its own.
Creating and reading blocks
| Tool | What it does |
|---|---|
vibe_coding_block_get_docs | Fetches the current vibe coding framework documentation |
vibe_coding_block_create | Creates a block on an existing page |
vibe_coding_block_get_code | Gets a block’s source code and its current settings |
vibe_coding_block_get_settings | Gets a block’s settings, actions, and data sources without the code |
Deleting a block
| Tool | What it does |
|---|---|
vibe_coding_block_delete | Removes a vibe coding block from its page |
Only vibe coding blocks can be deleted this way. Every other block (headers, lists, forms, navigation) is removed in the builder; the assistant will tell you so rather than finding a way around it.
Deleting takes the block’s data source connections with it, so there is nothing to disconnect first. The workspace integration stays connected, and no other block on the page is touched.
The block disappears from the builder straight away, but the live app keeps showing it until the app is published.
Editing code
| Tool | What it does |
|---|---|
vibe_coding_block_update_code | Replaces a block’s source code |
vibe_coding_block_update_code_search_replace | Makes a targeted edit to part of the code |
Settings and visibility
| Tool | What it does |
|---|---|
vibe_coding_block_update_settings | Changes the block’s editable settings |
vibe_coding_block_set_visibility | Controls who can see the block and which devices it renders on |
vibe_coding_block_set_action_visibility | Controls which user groups can run the block’s actions |
Editable settings are the fields you would fill in on the block’s panel in the builder: a title, a label, a threshold. Changing one doesn’t touch the code.
Version history
| Tool | What it does |
|---|---|
vibe_coding_block_list_versions | Lists a block’s versions, newest first |
vibe_coding_block_restore_version | Rolls a block back to an earlier version |
vibe_coding_block_duplicate_from_version | Creates a new block on the same page from one of an existing block’s versions, leaving the original alone |
Duplicating from a version is the safe way to try an alternative: you keep the working block and get a second one to experiment on.
Connecting data
A block that shows data needs a data source connected to it. The source is an integration belonging to the workspace, so this starts by browsing the workspace’s integrations to find the table you want.
| Tool | What it does |
|---|---|
vibe_coding_block_connect_data_source | Connects a table or sheet to the block, making it available to the code |
vibe_coding_block_disconnect_data_source | Removes a connection |
vibe_coding_block_set_data_source_sort | Sets the default sort order for a connected source |
vibe_coding_block_set_data_source_record_filters | Sets which records are visible through a connected source |
Sort order and record filters are the same settings as the Sources tab in the builder.