Skip to content

Beautiful Open-Source Form Builder

Add custom code and CSS settings for workspaces (#982)

Chirag Chhatrala26d84e1a2990
diff --git a/api/app/Http/Controllers/WorkspaceController.php b/api/app/Http/Controllers/WorkspaceController.php
index fca1d36f6..258593914 100644
--- a/api/app/Http/Controllers/WorkspaceController.php
+++ b/api/app/Http/Controllers/WorkspaceController.php
@@ -3,6 +3,7 @@
namespace App\Http\Controllers;
use App\Http\Requests\Workspace\CustomDomainRequest;
+use App\Http\Requests\Workspace\CustomCodeSettingsRequest;
use App\Http\Requests\Workspace\EmailSettingsRequest;
use App\Http\Resources\WorkspaceResource;
use App\Models\Workspace;
@@ -69,6 +70,26 @@ class WorkspaceController extends Controller
return new WorkspaceResource($request->workspace);
}
+ public function saveCustomCodeSettings(CustomCodeSettingsRequest $request)
+ {
+ $this->authorize('adminAction', $request->workspace);
+ if (!$request->workspace->is_pro) {
+ return $this->error([
+ 'message' => 'A Pro plan is required to use this feature.',
+ ], 403);
+ }
+
+ $validated = $request->validated();
+ $request->workspace->update([
+ 'settings' => array_merge($request->workspace->settings ?? [], [
+ 'custom_code' => $validated['custom_code'] ?? null,
+ 'custom_css' => $validated['custom_css'] ?? null,
+ ]),
+ ]);
+
+ return new WorkspaceResource($request->workspace);
+ }
+
public function delete(Workspace $workspace)
{
$this->authorize('delete', $workspace);
diff --git a/api/app/Http/Requests/Workspace/CustomCodeSettingsRequest.php b/api/app/Http/Requests/Workspace/CustomCodeSettingsRequest.php
new file mode 100644
index 000000000..bf5a6ae7c
--- /dev/null
+++ b/api/app/Http/Requests/Workspace/CustomCodeSettingsRequest.php
@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Http\Requests\Workspace;
+
+use App\Models\Workspace;
+use App\Rules\CssOnlyRule;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Http\Request;
+
+class CustomCodeSettingsRequest extends FormRequest
+{
+ public Workspace $workspace;
+
+ public function __construct(Request $request)
+ {
+ $this->workspace = $request->route('workspace');
+ }
+
+ /**
+ * Get the validation rules that apply to the request.
+ *
+ * @return array<string, mixed>
+ */
+ public function rules()
+ {
+ return [
+ 'custom_code' => ['string', 'nullable'],
+ 'custom_css' => ['string', 'nullable', new CssOnlyRule()],
+ ];
+ }
+}
diff --git a/api/app/Http/Resources/WorkspaceResource.php b/api/app/Http/Resources/WorkspaceResource.php
index 4da60fba6..47fcdb607 100644
--- a/api/app/Http/Resources/WorkspaceResource.php
+++ b/api/app/Http/Resources/WorkspaceResource.php
@@ -32,18 +32,25 @@ class WorkspaceResource extends JsonResource
public function toArray($request)
{
if ($this->restrictForGuest) {
- // Minimal public shape: avoid leaking workspace details
+ // Minimal public shape: include settings with custom code for form rendering
+ $settings = $this->settings ?? [];
return [
'id' => $this->resource->id,
'max_file_size' => $this->resource->max_file_size / 1000000,
+ 'settings' => $this->is_pro ? [
+ 'custom_code' => $settings['custom_code'] ?? null,
+ 'custom_css' => $settings['custom_css'] ?? null,
+ ] : [],
];
}
- return array_merge(parent::toArray($request), [
+ $data = array_merge(parent::toArray($request), [
'max_file_size' => $this->max_file_size / 1000000,
'is_readonly' => $this->isReadonlyUser($request->user()),
'is_admin' => $this->isAdminUser($request->user()),
'users_count' => $this->users_count,
]);
+
+ return $data;
}
}
diff --git a/api/app/Models/Workspace.php b/api/app/Models/Workspace.php
index 915b7af7b..7ea432723 100644
--- a/api/app/Models/Workspace.php
+++ b/api/app/Models/Workspace.php
@@ -25,7 +25,7 @@ class Workspace extends Model implements CachableAttributes
'icon',
'user_id',
'custom_domain',
- 'settings'
+ 'settings',
];
protected $dispatchesEvents = [
diff --git a/api/routes/api.php b/api/routes/api.php
index 5f1deae0a..9c872a741 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -145,6 +145,7 @@ Route::group(['middleware' => 'auth.multi'], function () {
)->name('forms.index');
Route::put('/custom-domains', [WorkspaceController::class, 'saveCustomDomain'])->name('save-custom-domains');
Route::put('/email-settings', [WorkspaceController::class, 'saveEmailSettings'])->name('save-email-settings');
+ Route::put('/custom-code-settings', [WorkspaceController::class, 'saveCustomCodeSettings'])->name('save-custom-code-settings');
Route::put('/', [WorkspaceController::class, 'update'])->name('update');
Route::delete('/', [WorkspaceController::class, 'delete'])->name('delete');
diff --git a/api/tests/Feature/Forms/FormTest.php b/api/tests/Feature/Forms/FormTest.php
index f6a1bee77..6e88ef81d 100644
--- a/api/tests/Feature/Forms/FormTest.php
+++ b/api/tests/Feature/Forms/FormTest.php
@@ -60,7 +60,6 @@ it('does not leak workspace details on public form fetch', function () {
->assertJsonPath('workspace.max_file_size', $workspace->max_file_size / 1000000);
$response->assertJsonMissingPath('workspace.users');
- $response->assertJsonMissingPath('workspace.settings');
$response->assertJsonMissingPath('workspace.is_admin');
$response->assertJsonMissingPath('workspace.is_readonly');
$response->assertJsonMissingPath('workspace.users_count');
diff --git a/api/tests/Feature/Workspaces/WorkspaceTest.php b/api/tests/Feature/Workspaces/WorkspaceTest.php
index c5ffe20cc..5db9c5500 100644
--- a/api/tests/Feature/Workspaces/WorkspaceTest.php
+++ b/api/tests/Feature/Workspaces/WorkspaceTest.php
@@ -228,3 +228,81 @@ it('includes users_count attribute', function () {
$workspace->flush();
expect($workspace->fresh()->users_count)->toBe(2);
});
+
+describe('Custom Code Settings', function () {
+ it('can save custom code settings for workspace', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+
+ $this->putJson(route('open.workspaces.save-custom-code-settings', $workspace), [
+ 'custom_code' => '<script>console.log("test")</script>',
+ 'custom_css' => 'body { color: red; }',
+ ])->assertSuccessful();
+
+ $workspace->refresh();
+ expect($workspace->settings['custom_code'])->toBe('<script>console.log("test")</script>');
+ expect($workspace->settings['custom_css'])->toBe('body { color: red; }');
+ });
+
+ it('prevents free users from saving custom code settings', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+
+ $this->putJson(route('open.workspaces.save-custom-code-settings', $workspace), [
+ 'custom_code' => '<script>test</script>',
+ ])->assertStatus(403);
+ });
+
+ it('validates custom CSS with CssOnlyRule', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+
+ $this->putJson(route('open.workspaces.save-custom-code-settings', $workspace), [
+ 'custom_css' => '<script>evil()</script>',
+ ])->assertStatus(422);
+ });
+
+ it('allows nullable custom code and css', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $workspace->update(['settings' => ['custom_code' => 'old', 'custom_css' => 'old']]);
+
+ $this->putJson(route('open.workspaces.save-custom-code-settings', $workspace), [
+ 'custom_code' => null,
+ 'custom_css' => null,
+ ])->assertSuccessful();
+
+ $workspace->refresh();
+ expect($workspace->settings['custom_code'])->toBeNull();
+ expect($workspace->settings['custom_css'])->toBeNull();
+ });
+
+ it('preserves other settings when saving custom code', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $workspace->update(['settings' => ['email_settings' => ['host' => 'smtp.test.com']]]);
+
+ $this->putJson(route('open.workspaces.save-custom-code-settings', $workspace), [
+ 'custom_code' => '<script>test</script>',
+ ])->assertSuccessful();
+
+ $workspace->refresh();
+ expect($workspace->settings['custom_code'])->toBe('<script>test</script>');
+ expect($workspace->settings['email_settings']['host'])->toBe('smtp.test.com');
+ });
+
+ it('prevents non-admin users from saving custom code settings', function () {
+ // Create workspace with an admin
+ $admin = $this->createProUser();
+ $workspace = $this->createUserWorkspace($admin);
+
+ // Create and login as a readonly user attached to the workspace
+ $readonlyUser = $this->createProUser();
+ $workspace->users()->attach($readonlyUser, ['role' => 'user']);
+ $this->actingAsProUser($readonlyUser);
+
+ $this->putJson(route('open.workspaces.save-custom-code-settings', $workspace), [
+ 'custom_code' => '<script>test</script>',
+ ])->assertStatus(403);
+ });
+});
diff --git a/client/components/workspaces/settings/CustomCode.vue b/client/components/workspaces/settings/CustomCode.vue
new file mode 100644
index 000000000..d76393557
--- /dev/null
+++ b/client/components/workspaces/settings/CustomCode.vue
@@ -0,0 +1,188 @@
+<template>
+ <div class="space-y-4">
+ <div class="flex flex-col flex-wrap items-start justify-between gap-4 sm:flex-row sm:items-center">
+ <div class="flex-1">
+ <h3 class="text-lg font-medium text-neutral-900">
+ Custom Code <ProTag
+ class="mb-2 block"
+ upgrade-modal-title="Upgrade to Unlock Custom Code Capabilities"
+ upgrade-modal-description="On the Free plan, you can explore custom code features within the workspace settings. Upgrade your plan to implement custom scripts, styles, and advanced tracking in all your workspace forms. Elevate your forms' functionality and design with unlimited customization options."
+ />
+ </h3>
+ <p class="mt-1 text-sm text-neutral-500">
+ The code will be injected in the <b>head</b> section of all forms in this workspace. Workspace code is applied first, then form-specific code (if any).
+ </p>
+ </div>
+ <UButton
+ label="Help"
+ icon="i-heroicons-question-mark-circle"
+ variant="outline"
+ color="neutral"
+ @click="crisp.openHelpdeskArticle('how-do-i-add-custom-code-to-my-form-1amadj3')"
+ />
+ </div>
+
+ <UAlert
+ v-if="!workspace.is_pro"
+ icon="i-heroicons-user-group-20-solid"
+ class="mb-4"
+ color="warning"
+ variant="subtle"
+ title="Pro plan required"
+ description="Please upgrade your account to use workspace-level custom code."
+ :actions="[{
+ label: 'Try Pro plan',
+ color: 'warning',
+ variant: 'solid',
+ onClick: () => openSubscriptionModal()
+ }]"
+ />
+
+ <VForm size="sm">
+ <form
+ @submit.prevent="saveChanges"
+ >
+ <div class="space-y-4">
+ <div>
+ <CodeInput
+ :allow-fullscreen="true"
+ name="custom_code"
+ class="mt-4"
+ :form="customCodeForm"
+ :disabled="!canUseCustomCode"
+ :help="customCodeHelp"
+ label="Custom Code"
+ placeholder="<script>console.log('Hello World!')</script>"
+ />
+ </div>
+
+ <div class="pt-6">
+ <div class="flex flex-col flex-wrap items-start justify-between gap-4 sm:flex-row sm:items-center">
+ <div>
+ <h3 class="text-lg font-medium text-neutral-900">
+ Custom CSS <ProTag
+ class="mb-2 block"
+ upgrade-modal-title="Upgrade to Unlock Custom CSS"
+ upgrade-modal-description="On the Free plan, you can explore custom CSS within the workspace settings. Upgrade to apply custom styles to all your workspace forms."
+ />
+ </h3>
+ <p class="mt-1 text-sm text-neutral-500">
+ The CSS will be injected in the <b>head</b> of all forms in this workspace.
+ </p>
+ </div>
+ <UButton
+ label="Help"
+ icon="i-heroicons-question-mark-circle"
+ variant="outline"
+ color="neutral"
+ @click="crisp.openHelpdeskArticle('can-i-style-my-form-with-some-custom-css-code-1v3dlr9')"
+ />
+ </div>
+ <CodeInput
+ :allow-fullscreen="true"
+ language-mode="css"
+ name="custom_css"
+ class="mt-4"
+ :form="customCodeForm"
+ :disabled="!workspace.is_pro"
+ help="CSS only. Example: body { background: #f8fafc }"
+ label="Custom CSS"
+ placeholder="body { background: #f8fafc }"
+ />
+ </div>
+ </div>
+
+ <div class="mt-4">
+ <UButton
+ type="submit"
+ :loading="customCodeForm.busy"
+ :disabled="!workspace.is_pro"
+ color="primary"
+ >
+ Save Changes
+ </UButton>
+ </div>
+ </form>
+ </VForm>
+ </div>
+</template>
+
+<script setup>
+import ProTag from "~/components/app/ProTag.vue"
+
+const alert = useAlert()
+const crisp = useCrisp()
+const { current: workspace } = useCurrentWorkspace()
+const { openSubscriptionModal: openModal } = useAppModals()
+const { invalidateAll } = useWorkspaces()
+
+const openSubscriptionModal = () => {
+ openModal({ modal_title: 'Upgrade to use workspace level custom code' })
+}
+
+const customCodeForm = useForm({
+ custom_code: '',
+ custom_css: ''
+})
+
+const hasCustomDomain = computed(() => {
+ return workspace.value?.custom_domains && workspace.value.custom_domains.length > 0
+})
+
+const selfHosted = computed(() => !!useFeatureFlag('self_hosted', false))
+const allowSelfHosted = computed(() => !!useFeatureFlag('custom_code.enable_self_hosted', false))
+
+const canUseCustomCode = computed(() => {
+ if (!workspace.value?.is_pro) return false
+ return hasCustomDomain.value || (selfHosted.value && allowSelfHosted.value)
+})
+
+const customCodeHelp = computed(() => {
+ if (canUseCustomCode.value) {
+ return 'Saves changes and visit any form page to test. Workspace code is applied to all forms in this workspace.'
+ }
+ if (selfHosted.value && !allowSelfHosted.value && !hasCustomDomain.value) {
+ return 'Custom code is disabled for safety on self-hosted. Enable via CUSTOM_CODE_ENABLE_SELF_HOSTED=true. See technical docs: https://docs.opnform.com/introduction'
+ }
+ return 'Custom code requires a Pro plan and a custom domain configured for this workspace.'
+})
+
+const saveChanges = () => {
+ if (!workspace.value?.is_pro) return
+
+ customCodeForm
+ .put(`/open/workspaces/${workspace.value.id}/custom-code-settings`, {
+ data: {
+ custom_code: customCodeForm.custom_code || null,
+ custom_css: customCodeForm.custom_css || null,
+ },
+ })
+ .then((_data) => {
+ alert.success("Custom code settings saved.")
+ // Invalidate workspace cache to refresh data
+ invalidateAll()
+ })
+ .catch((error) => {
+ alert.error("Failed to update custom code settings: " + (error.response?.data?.message || error.message))
+ })
+}
+
+const initCustomCode = () => {
+ if (!workspace.value) return
+ const settings = workspace.value.settings || {}
+ customCodeForm.custom_code = settings.custom_code || ''
+ customCodeForm.custom_css = settings.custom_css || ''
+}
+
+onMounted(() => {
+ initCustomCode()
+})
+
+watch(
+ () => workspace.value,
+ () => {
+ initCustomCode()
+ },
+ { deep: true }
+)
+</script>
diff --git a/client/components/workspaces/settings/Modal.vue b/client/components/workspaces/settings/Modal.vue
index 65cbcffb8..2ab41f60a 100644
--- a/client/components/workspaces/settings/Modal.vue
+++ b/client/components/workspaces/settings/Modal.vue
@@ -49,6 +49,14 @@
<LazyWorkspacesSettingsSso />
</SettingsModalPage>
+ <SettingsModalPage
+ v-if="workspace && workspace.is_admin"
+ id="custom-code"
+ label="Custom Code"
+ icon="i-heroicons-code-bracket"
+ >
+ <LazyWorkspacesSettingsCustomCode />
+ </SettingsModalPage>
</SettingsModal>
</template>
@@ -57,6 +65,7 @@ import { computed } from 'vue'
import SettingsModal from '~/components/pages/settings/SettingsModal.vue'
import SettingsModalPage from '~/components/pages/settings/SettingsModalPage.vue'
import LazyWorkspacesSettingsSso from './sso/index.vue'
+import LazyWorkspacesSettingsCustomCode from './CustomCode.vue'
const emit = defineEmits(['update:activeTab'])
diff --git a/client/pages/forms/[slug]/index.vue b/client/pages/forms/[slug]/index.vue
index cbf7a8e92..b1dcf28d9 100644
--- a/client/pages/forms/[slug]/index.vue
+++ b/client/pages/forms/[slug]/index.vue
@@ -141,8 +141,10 @@ onMounted(() => {
const canExecuteCustomCode = isCustomDomain || (isSelfHosted && allowSelfHosted)
- if (form.value.custom_code && canExecuteCustomCode) {
- const scriptEl = document.createRange().createContextualFragment(form.value.custom_code)
+ // Concatenate workspace and form custom code when injecting
+ const codeToInject = effectiveCustomCode.value
+ if (codeToInject && canExecuteCustomCode) {
+ const scriptEl = document.createRange().createContextualFragment(codeToInject)
try {
document.head.append(scriptEl)
} catch (e) {
@@ -244,6 +246,28 @@ const getHtmlClass = computed(() => {
}
})
+// Concatenate workspace and form custom code (workspace first, then form)
+// Only when actually injecting into head tag
+const effectiveCustomCode = computed(() => {
+ const workspaceSettings = form.value?.workspace?.settings || {}
+ const workspaceCode = workspaceSettings.custom_code || ''
+ const formCode = form.value?.custom_code || ''
+
+ if (!workspaceCode && !formCode) return null
+
+ return (workspaceCode + '\n' + formCode).trim()
+})
+
+const effectiveCustomCss = computed(() => {
+ const workspaceSettings = form.value?.workspace?.settings || {}
+ const workspaceCss = workspaceSettings.custom_css || ''
+ const formCss = form.value?.custom_css || ''
+
+ if (!workspaceCss && !formCss) return null
+
+ return (workspaceCss + '\n' + formCss).trim()
+})
+
useHead({
htmlAttrs: {
dir: () => form.value?.layout_rtl ? 'rtl' : 'ltr',
@@ -269,8 +293,8 @@ useHead({
},
] : {},
script: [{ src: '/widgets/iframeResizer.contentWindow.min.js' }],
- style: computed(() => form.value?.custom_css ? [
- { key: 'custom-css', textContent: form.value.custom_css }
+ style: computed(() => effectiveCustomCss.value ? [
+ { key: 'custom-css', textContent: effectiveCustomCss.value }
] : [])
})