Beautiful Open-Source Form Builder
Better self-hosted onboarding (#821)
Julien Nahum2b7532a3ab49
diff --git a/api/app/Console/Commands/InitProjectCommand.php b/api/app/Console/Commands/InitProjectCommand.phpdeleted file mode 100644index 3f6f55d04..000000000--- a/api/app/Console/Commands/InitProjectCommand.php+++ /dev/null@@ -1,48 +0,0 @@-<?php--namespace App\Console\Commands;--use App\Models\User;-use Illuminate\Console\Command;--class InitProjectCommand extends Command-{- /**- * The name and signature of the console command.- *- * @var string- */- protected $signature = 'app:init-project';-- /**- * The console command description.- *- * @var string- */- protected $description = 'Creates the default admin user';-- /**- * Execute the console command.- */- public function handle()- {- if (!config('app.self_hosted')) {- $this->error('This command can only be run in self-hosted mode.');- return;- }-- // Check if there are any existing users or if the ID increment is not at 0- if (User::max('id') !== null) {- $this->error('Users already exist in the database or the User table is not empty. Aborting initialization.');- return;- }-- User::create([- 'name' => 'Admin',- 'email' => '[email protected]',- 'password' => bcrypt('password'),- ]);- $this->info('Admin user created with default credentials: [email protected] / password');- return 0;- }-}diff --git a/api/app/Http/Controllers/Auth/RegisterController.php b/api/app/Http/Controllers/Auth/RegisterController.phpindex 90872f0d2..29657edd3 100644--- a/api/app/Http/Controllers/Auth/RegisterController.php+++ b/api/app/Http/Controllers/Auth/RegisterController.php@@ -73,12 +73,16 @@ class RegisterController extends Controller'email' => 'required|email:filter|max:255|unique:users|indisposable','password' => 'required|min:6|confirmed','hear_about_us' => 'required|string',- 'agree_terms' => ['required', Rule::in([true])],'appsumo_license' => ['nullable'],'invite_token' => ['nullable', 'string'],'utm_data' => ['nullable', 'array'],];+ // Only require terms agreement in cloud/hosted mode, not self-hosted+ if (!config('app.self_hosted')) {+ $rules['agree_terms'] = ['required', Rule::in([true])];+ }+if (config('services.re_captcha.secret_key')) {$rules['g-recaptcha-response'] = [new ValidReCaptcha()];}@@ -114,13 +118,22 @@ class RegisterController extends Controller$this->appsumoLicense = AppSumoAuthController::registerWithLicense($user, $data['appsumo_license'] ?? null);+ // Clear feature flags cache when first user is created (affects setup_required flag)+ if (config('app.self_hosted') && $user->id === 1) {+ \Illuminate\Support\Facades\Cache::forget('feature_flags');+ }+return $user;}private function checkRegistrationAllowed(array $data){if (config('app.self_hosted') && !array_key_exists('invite_token', $data) && (app()->environment() !== 'testing')) {- response()->json(['message' => 'Registration is not allowed in self host mode'], 400)->throwResponse();+ // Allow registration during setup (when no users exist)+ if (!\App\Models\User::max('id')) {+ return; // Setup mode - allow registration+ }+ return response()->json(['message' => 'Registration is not allowed.'], 400)->throwResponse();}}diff --git a/api/app/Http/Controllers/Content/FeatureFlagsController.php b/api/app/Http/Controllers/Content/FeatureFlagsController.phpindex b1390ee46..d032b311b 100644--- a/api/app/Http/Controllers/Content/FeatureFlagsController.php+++ b/api/app/Http/Controllers/Content/FeatureFlagsController.php@@ -12,6 +12,7 @@ class FeatureFlagsController extends Controller$featureFlags = Cache::remember('feature_flags', 3600, function () {return ['self_hosted' => config('app.self_hosted', true),+ 'setup_required' => config('app.self_hosted', true) && !\App\Models\User::max('id'),'custom_domains' => config('custom-domains.enabled', false),'ai_features' => !empty(config('services.openai.api_key')),'version' => $this->getAppVersion(),diff --git a/api/app/Http/Controllers/Settings/ProfileController.php b/api/app/Http/Controllers/Settings/ProfileController.phpindex b790711f1..db74fac42 100644--- a/api/app/Http/Controllers/Settings/ProfileController.php+++ b/api/app/Http/Controllers/Settings/ProfileController.php@@ -3,9 +3,7 @@namespace App\Http\Controllers\Settings;use App\Http\Controllers\Controller;-use App\Models\Workspace;use Illuminate\Http\Request;-use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\RateLimiter;use Illuminate\Http\Exceptions\ThrottleRequestsException;@@ -45,41 +43,4 @@ class ProfileController extends Controller'email' => strtolower($request->email),]);}-- // For self-hosted mode, only admin can update their credentials- public function updateAdminCredentials(Request $request)- {- $request->validate([- 'email' => 'required|email|not_in:[email protected]',- 'password' => 'required|min:6|confirmed|not_in:password',- ], [- 'email.not_in' => "Please provide email address other than '[email protected]'",- 'password.not_in' => "Please another password other than 'password'."- ]);-- $user = $request->user();- $user->update([- 'email' => $request->email,- 'password' => bcrypt($request->password),- ]);-- Cache::forget('initial_user_setup_complete');- Cache::forget('max_user_id');-- $workspace = Workspace::create([- 'name' => 'My Workspace',- 'icon' => 'π§ͺ',- ]);-- $user->workspaces()->sync([- $workspace->id => [- 'role' => 'admin',- ],- ], false);-- return $this->success([- 'message' => 'Congratulations, your account credentials have been updated successfully.',- 'user' => $user,- ]);- }}diff --git a/api/app/Http/Kernel.php b/api/app/Http/Kernel.phpindex 7bf46b3a1..43940ab77 100644--- a/api/app/Http/Kernel.php+++ b/api/app/Http/Kernel.php@@ -13,7 +13,6 @@ use App\Http\Middleware\IsModerator;use App\Http\Middleware\IsNotSubscribed;use App\Http\Middleware\IsSubscribed;use App\Http\Middleware\RequireProPlan;-use App\Http\Middleware\SelfHostedCredentialsMiddleware;use Illuminate\Foundation\Http\Kernel as HttpKernel;use App\Http\Middleware\CheckUserIsBlocked;@@ -90,7 +89,7 @@ class Kernel extends HttpKernel\App\Http\Middleware\EncryptCookies::class,\Illuminate\Session\Middleware\StartSession::class,\Illuminate\Routing\Middleware\SubstituteBindings::class,- SelfHostedCredentialsMiddleware::class,+ImpersonationMiddleware::class,CheckUserIsBlocked::class,],diff --git a/api/app/Http/Middleware/SelfHostedCredentialsMiddleware.php b/api/app/Http/Middleware/SelfHostedCredentialsMiddleware.phpdeleted file mode 100644index 49f8ffc97..000000000--- a/api/app/Http/Middleware/SelfHostedCredentialsMiddleware.php+++ /dev/null@@ -1,66 +0,0 @@-<?php--namespace App\Http\Middleware;--use Closure;-use Illuminate\Http\Request;-use Symfony\Component\HttpFoundation\Response;-use Illuminate\Support\Facades\Cache;-use App\Models\User;--class SelfHostedCredentialsMiddleware-{- public const ALLOWED_ROUTES = [- 'login',- 'credentials.update',- 'user.current',- 'logout',- ];-- /**- * Handle an incoming request.- *- * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next- */- public function handle(Request $request, Closure $next): Response- {- if (app()->environment('testing')) {- return $next($request);- }-- if (in_array($request->route()->getName(), self::ALLOWED_ROUTES)) {- return $next($request);- }-- if (- config('app.self_hosted') &&- $request->user() &&- !$this->isInitialSetupComplete()- ) {- return response()->json([- 'message' => 'You must change your credentials when in self-hosted mode',- 'type' => 'error',- ], Response::HTTP_FORBIDDEN);- }-- return $next($request);- }-- private function isInitialSetupComplete(): bool- {- return (bool) Cache::remember('initial_user_setup_complete', 60 * 60, function () {- $maxUserId = $this->getMaxUserId();- if ($maxUserId === 0) {- return false;- }- return !User::where('email', '[email protected]')->exists();- });- }-- private function getMaxUserId(): int- {- return (int) Cache::remember('max_user_id', 60 * 60, function () {- return User::max('id') ?? 0;- });- }-}diff --git a/api/routes/api.php b/api/routes/api.phpindex 176b88e77..2cfea04d2 100644--- a/api/routes/api.php+++ b/api/routes/api.php@@ -48,7 +48,7 @@ if (config('app.self_hosted')) {Route::group(['middleware' => 'auth.multi'], function () {Route::post('logout', [LoginController::class, 'logout'])->name('logout');- Route::post('update-credentials', [ProfileController::class, 'updateAdminCredentials'])->name('credentials.update');+Route::get('user', [UserController::class, 'current'])->name('user.current');Route::delete('user', [UserController::class, 'deleteAccount']);diff --git a/client/api/auth.js b/client/api/auth.jsindex 3ae7d8252..c0dadde9d 100644--- a/client/api/auth.js+++ b/client/api/auth.js@@ -6,7 +6,7 @@ export const authApi = {user: {get: (options) => apiService.get('/user', options),delete: () => apiService.delete('/user'),- updateCredentials: (data) => apiService.post('/update-credentials', data),+updateProfile: (data) => apiService.patch('/settings/profile', data)},diff --git a/client/components/forms/heavy/CodeInput.client.vue b/client/components/forms/heavy/CodeInput.client.vueindex b286e7cb0..338e43779 100644--- a/client/components/forms/heavy/CodeInput.client.vue+++ b/client/components/forms/heavy/CodeInput.client.vue@@ -118,12 +118,10 @@ const isFullscreen = ref(false)const openFullscreen = () => {isFullscreen.value = true- console.log('openFullscreen')}const closeFullscreen = () => {isFullscreen.value = false- console.log('closeFullscreen')}// Handle keyboard shortcutsdiff --git a/client/components/open/forms/components/FormWorkspaceModal.vue b/client/components/open/forms/components/FormWorkspaceModal.vueindex 8d7e320b2..5bae881b5 100644--- a/client/components/open/forms/components/FormWorkspaceModal.vue+++ b/client/components/open/forms/components/FormWorkspaceModal.vue@@ -74,7 +74,7 @@ const crisp = useCrisp()const selectedWorkspace = ref(null)const props = defineProps({- show: { type: Boolean, required: true },+ show: { type: Boolean, required: true },form: { type: Object, required: true },})diff --git a/client/components/open/tables/OpenTable.vue b/client/components/open/tables/OpenTable.vueindex 01ec97f4b..6fb1f325f 100644--- a/client/components/open/tables/OpenTable.vue+++ b/client/components/open/tables/OpenTable.vue@@ -305,7 +305,6 @@ const downloadAsCsv = () => {formsApi.submissions.export(props.form.id, {columns: columnVisibility.value}).then(data => {- console.log(data)// Convert string to Blob if neededlet blobdiff --git a/client/components/pages/auth/components/RegisterForm.vue b/client/components/pages/auth/components/RegisterForm.vueindex 949ac61b4..3333fbd84 100644--- a/client/components/pages/auth/components/RegisterForm.vue+++ b/client/components/pages/auth/components/RegisterForm.vue@@ -24,7 +24,7 @@/><select-input- v-if="!disableEmail"+ v-if="!disableEmail && !isSetup"name="hear_about_us":options="hearAboutUsOptions":form="form"@@ -71,6 +71,7 @@name="agree_terms"class="my-3":required="true"+ v-if="!useFeatureFlag('self_hosted')"><template #label><label for="agree_terms">@@ -105,7 +106,7 @@label="Create account"/>- <template v-if="useFeatureFlag('services.google.auth') && !useFeatureFlag('self_hosted')">+ <template v-if="useFeatureFlag('services.google.auth') && !useFeatureFlag('self_hosted') && !isSetup"><p class="text-neutral-500 text-sm text-center my-4">OR</p>@@ -122,7 +123,7 @@/></template>- <p class="text-neutral-500 mt-4 text-sm text-center">+ <p v-if="!isSetup" class="text-neutral-500 mt-4 text-sm text-center">Already have an account?<av-if="isQuick"@@ -142,7 +143,7 @@<!-- Google One Tap --><ClientOnly>- <GoogleOneTap context="signup" />+ <GoogleOneTap v-if="!isSetup" context="signup" /></ClientOnly></template>@@ -157,10 +158,15 @@ const props = defineProps({required: false,default: false,},+ isSetup: {+ type: Boolean,+ required: false,+ default: false,+ },})// Emits-defineEmits(['openLogin'])+const emit = defineEmits(['openLogin', 'registered'])// Composablesconst { $utm } = useNuxtApp()@@ -239,6 +245,11 @@ onMounted(() => {}form.invite_token = route.query?.invite_token}++ // Set default hear_about_us for setup mode+ if (props.isSetup) {+ form.hear_about_us = 'setup'+ }})// Methods@@ -252,13 +263,19 @@ const register = () => {source: form.hear_about_us}}).then(() => {+ if (props.isSetup) {+ // In setup mode, emit registered event instead of showing alert/redirecting+ emit('registered')+ } else {useAlert().success({title: "Welcome to OpnForm π",...!props.isQuick ? {description: "Time to create your first form!"} : {}})redirect()+ }}).catch((err) => {- useAlert().error(err.response?._data?.message)+ console.error(err)+ useAlert().error(err.response?._data?.message ?? "Something went wrong. Please try again.")}).finally(() => {// Reset captcha after submissionif (import.meta.client && reCaptchaSiteKey.value) {diff --git a/client/components/provider/widget/TelegramWidget.vue b/client/components/provider/widget/TelegramWidget.vueindex 5e644329c..703b5da04 100644--- a/client/components/provider/widget/TelegramWidget.vue+++ b/client/components/provider/widget/TelegramWidget.vue@@ -24,8 +24,6 @@</template><script setup>-import { useFeatureFlagsStore } from '~/stores/featureFlags'-defineProps({service: {type: Object,@@ -35,8 +33,7 @@ defineProps({const emit = defineEmits(['auth-data'])-const featureFlagsStore = useFeatureFlagsStore()-const botId = computed(() => featureFlagsStore.getFlag('services.telegram.bot_id'))+const botId = computed(() => useFeatureFlag('services.telegram.bot_id'))const loadTelegramWidget = () => {if (!botId.value) returndiff --git a/client/composables/index.js b/client/composables/index.jsindex 9f0a93b4c..7a966f687 100644--- a/client/composables/index.js+++ b/client/composables/index.js@@ -13,4 +13,4 @@ export { useFormsList } from './query/forms/useFormsList.js'export { useFormSubmissions } from './query/forms/useFormSubmissions.js'export { useFormIntegrations } from './query/forms/useFormIntegrations.js'export { useFormAI } from './query/forms/useFormAI.js'-export { useFormStats } from './query/forms/useFormStats.js'\ No newline at end of file+export { useFormStats } from './query/forms/useFormStats.js'\ No newline at end of filediff --git a/client/composables/query/forms/useFormIntegrations.js b/client/composables/query/forms/useFormIntegrations.jsindex cc8efacb7..649079025 100644--- a/client/composables/query/forms/useFormIntegrations.js+++ b/client/composables/query/forms/useFormIntegrations.js@@ -2,6 +2,8 @@ import { useQueryClient, useQuery, useMutation } from '@tanstack/vue-query'import { formsApi } from '~/api/forms'import integrationsList from '~/data/forms/integrations.json'import { unref } from 'vue'+import { useAuth } from '~/composables/query/useAuth.js'+import { useFeatureFlag } from '~/composables/useFeatureFlag.js'export function useFormIntegrations() {const queryClient = useQueryClient()@@ -20,12 +22,11 @@ export function useFormIntegrations() {// Computed property for available integrations based on user subscription and feature flagsconst availableIntegrations = computed(() => {- const featureFlagsStore = useFeatureFlagsStore()if (!userData.value) return integrations.valueconst enrichedIntegrations = new Map()for (const [key, integration] of integrations.value.entries()) {- if (featureFlagsStore.getFlag(`integrations.${key}`, true)) {+ if (useFeatureFlag(`integrations.${key}`, true)) {enrichedIntegrations.set(key, {...integration,id: key,diff --git a/client/composables/query/forms/useForms.js b/client/composables/query/forms/useForms.jsindex 4cb9b9a08..93aba0dd5 100644--- a/client/composables/query/forms/useForms.js+++ b/client/composables/query/forms/useForms.js@@ -68,7 +68,6 @@ export function useForms() {onSuccess: (updatedForm) => {const form = updatedForm.formconst currentFormId = toValue(formId)- console.log(updatedForm)// Update individual form cachequeryClient.setQueryData(['forms', currentFormId], form)diff --git a/client/composables/query/useAuth.js b/client/composables/query/useAuth.jsindex 58536af6b..2769e04f8 100644--- a/client/composables/query/useAuth.js+++ b/client/composables/query/useAuth.js@@ -37,21 +37,7 @@ export function useAuth() {}// Mutations- const updateCredentials = (options = {}) => {- return useMutation({- mutationFn: (data) => authApi.user.updateCredentials(data),- onSuccess: (updatedUser) => {- // Update user cache with optimistic updates- queryClient.setQueryData(['user'], (old) => {- const newData = old ? { ...old, ...updatedUser } : updatedUser- // Re-initialize service clients with updated data- initServiceClients(newData)- return newData- })- },- ...options- })- }+const deleteAccount = (options = {}) => {return useMutation({@@ -164,7 +150,6 @@ export function useAuth() {login,register,updateProfile,- updateCredentials,deleteAccount,logout,oauthCallback,diff --git a/client/composables/useFeatureFlag.js b/client/composables/useFeatureFlag.jsindex e377a9776..10376f630 100644--- a/client/composables/useFeatureFlag.js+++ b/client/composables/useFeatureFlag.js@@ -1,5 +1,45 @@-+// Main composable - returns raw value (not computed)export function useFeatureFlag(flagName, defaultValue = null) {- const featureStore = useFeatureFlagsStore()- return featureStore.getFlag(flagName, defaultValue)+ const featureFlags = useState('featureFlags', () => ({}))+ return getFlagFromObject(unref(featureFlags), flagName, defaultValue)+}++// Extended composable for flag management+export function useFeatureFlags() {+ const nuxtApp = useNuxtApp()++ return {+ // Get all flags+ flags: () => {+ return {+ data: useState('featureFlags', () => ({})),+ suspense: () => Promise.resolve() // No-op since loaded via SSR+ }+ },++ // Get individual flag (for backward compatibility)+ getFlag: (flagName, defaultValue = null) => {+ return useFeatureFlag(flagName, defaultValue)+ },++ // Invalidate/refresh flags from API (client-only)+ async invalidateFlags() {+ if (import.meta.server) {+ console.warn('Cannot invalidate feature flags on server-side')+ return+ }++ return await nuxtApp.$refreshFeatureFlags()+ }+ }+}++// Helper to extract flag value from nested object+function getFlagFromObject(flags, flagName, defaultValue) {+ if (!flags || typeof flags !== 'object') return defaultValue++ return flagName.split('.').reduce((acc, part) => {+ if (acc === undefined || acc === null) return defaultValue+ return acc && acc[part] !== undefined ? acc[part] : defaultValue+ }, flags)}\ No newline at end of filediff --git a/client/middleware/self-hosted-credentials.js b/client/middleware/self-hosted-credentials.jsdeleted file mode 100644index 62f40348d..000000000--- a/client/middleware/self-hosted-credentials.js+++ /dev/null@@ -1,11 +0,0 @@-export default defineNuxtRouteMiddleware(async () => {- const { isAuthenticated } = useIsAuthenticated()- const { user } = useAuth()- const { data: userData } = user()-- if (useFeatureFlag('self_hosted')) {- if (isAuthenticated.value && userData.value?.email === '[email protected]') {- throw createError({ statusCode: 403, statusMessage: 'Please update your credentials' })- }- }-})\ No newline at end of filediff --git a/client/middleware/setup-redirect.global.js b/client/middleware/setup-redirect.global.jsnew file mode 100644index 000000000..dffacbb48--- /dev/null+++ b/client/middleware/setup-redirect.global.js@@ -0,0 +1,41 @@+import { sendRedirect } from 'h3'+import { unref } from 'vue'++/**+ * Global middleware to redirect to setup page when setup is required+ * Only runs in self-hosted mode when no users exist in database+ */+export default defineNuxtRouteMiddleware(async (to) => {+ // Skip redirect for setup page itself and API routes+ if (to.path.startsWith('/setup') || to.path.startsWith('/api')) {+ return+ }++ try {+ // Use the feature flag shortcut (loaded by 00.feature-flags.global.js)+ const setupRequiredRef = useFeatureFlag('setup_required', false)+ const setupRequired = unref(setupRequiredRef) // Handle both ref and non-ref values++ if (!setupRequired) {+ return // Setup not required, continue normally+ }++ // Server-side redirect (SSR)+ if (import.meta.server) {+ const event = useRequestEvent()+ if (event) {+ await sendRedirect(event, '/setup', 302)+ return+ }+ }++ // Client-side redirect fallback+ if (import.meta.client) {+ await navigateTo('/setup')+ }++ } catch (error) {+ // On error, don't block navigation - log and continue+ console.warn('Setup redirect middleware failed:', error)+ }+})\ No newline at end of filediff --git a/client/package.json b/client/package.jsonindex f7e6e4c90..7011d5c4a 100644--- a/client/package.json+++ b/client/package.json@@ -4,7 +4,7 @@"type": "module","scripts": {"build": "NODE_OPTIONS='--max-old-space-size=8192' nuxt build",- "dev": "export NODE_TLS_REJECT_UNAUTHORIZED=0; NODE_OPTIONS='--max-old-space-size=8192' nuxt dev",+ "dev": "export NODE_TLS_REJECT_UNAUTHORIZED=0; nuxt dev","docker-dev": "export NODE_TLS_REJECT_UNAUTHORIZED=0; nuxt dev --host 0.0.0.0","generate": "export NODE_TLS_REJECT_UNAUTHORIZED=0; nuxt generate","preview": "nuxt preview",diff --git a/client/pages/home.vue b/client/pages/home.vueindex 6d9bb2537..ca971c3c1 100644--- a/client/pages/home.vue+++ b/client/pages/home.vue@@ -134,7 +134,7 @@ import TrackClick from '~/components/global/TrackClick.vue'import UpgradeBanner from "~/components/dashboard/UpgradeBanner.vue"definePageMeta({- middleware: ["auth", "self-hosted-credentials"],+ middleware: ["auth"],layout: "dashboard",})diff --git a/client/pages/setup.vue b/client/pages/setup.vuenew file mode 100644index 000000000..15507b051--- /dev/null+++ b/client/pages/setup.vue@@ -0,0 +1,72 @@+<template>+ <div class="min-h-screen bg-neutral-50 flex flex-col justify-center sm:px-6 lg:px-8 py-10">+ <div class="sm:mx-auto sm:w-full sm:max-w-md">+ <div class="flex justify-center items-center mb-6">+ <img+ src="/img/logo.svg"+ alt="OpnForm logo"+ class="w-8 h-8"+ >+ <h1 class="ml-2 text-xl font-semibold text-black">+ OpnForm+ </h1>+ </div>++ <p class="mt-2 text-center text-sm text-neutral-600">+ Welcome to OpnForm! Let's get you set up. Create your admin account to start building beautiful forms.+ </p>+ </div>++ <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">+ <div class="bg-white py-8 px-4 shadow-sm sm:rounded-sm sm:px-10">+ <RegisterForm+ :is-quick="false"+ :is-setup="true"+ @registered="handleSetupComplete"+ />+ </div>+ </div>+ </div>+</template>++<script setup>+import RegisterForm from '~/components/pages/auth/components/RegisterForm.vue'++const { invalidateFlags } = useFeatureFlags()+const router = useRouter()++// Check if setup is required+const setupRequired = useFeatureFlag('setup_required', false)+const selfHosted = useFeatureFlag('self_hosted', false)++// Show 404 if setup not required or not self-hosted+if (!setupRequired || !selfHosted) {+ throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })+}++// SEO+useOpnSeoMeta({+ title: "Setup - OpnForm",+ description: "Set up your OpnForm instance",+ robots: "noindex, nofollow"+})++definePageMeta({+ layout: 'empty'+})++// Handle successful setup completion+const handleSetupComplete = async () => {+ // Invalidate feature flags to update setup_required status+ await invalidateFlags()++ // Show success message+ useAlert().success({+ title: "Setup Complete! π",+ description: "Your OpnForm instance is ready. Time to create your first form!"+ })++ // Redirect to dashboard+ router.push({ name: "home" })+}+</script>\ No newline at end of filediff --git a/client/pages/update-credentials.vue b/client/pages/update-credentials.vuedeleted file mode 100644index 5d4bb31be..000000000--- a/client/pages/update-credentials.vue+++ /dev/null@@ -1,120 +0,0 @@-<template>- <div class=" bg-neutral-50 flex flex-col justify-center sm:px-6 lg:px-8 py-10 flex-grow">- <div class="sm:mx-auto sm:w-full sm:max-w-md">- <h2 class="text-center text-3xl font-bold tracking-tight text-neutral-900">- Welcome to OpnForm!- </h2>- <p class="mt-2 text-center text-sm text-neutral-600">- You're using the self-hosted version of OpnForm and need to set up your account.- Please enter your email and create a password to continue.- </p>- </div>-- <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">- <div class="bg-white py-8 px-4 shadow-sm sm:rounded-sm sm:px-10">- <form- @submit.prevent="updateCredentials"- >- <!-- Email -->- <text-input- name="email"- :form="form"- label="Email"- :required="true"- placeholder="Your email address"- />-- <!-- Password -->- <text-input- native-type="password"- placeholder="Your password"- name="password"- :form="form"- label="Password"- :required="true"- />-- <!-- Password Confirmation-->- <text-input- native-type="password"- :form="form"- :required="true"- placeholder="Enter confirm password"- name="password_confirmation"- label="Confirm Password"- />-- <!-- Submit Button -->- <div class="mt-6">- <UButton- class="w-full justify-center"- :loading="form.busy || loading"- type="submit"- label="Update Credentials"- />- </div>-- <!-- Cancel Link -->- <div class="mt-4 text-center">- <button- type="button"- class="text-sm text-neutral-600 hover:text-neutral-900"- @click="logout"- >- Cancel and return to login- </button>- </div>- </form>- </div>- </div>- </div>-</template>--<script setup>-import { onMounted } from "vue"--const { data: user, logout: logoutMutationFactory } = useAuth()-const router = useRouter()-const loading = ref(false)-const logoutMutation = logoutMutationFactory()-const form = useForm({- name: "",- email: "",- password: "",- password_confirmation: "",- agree_terms: false,- appsumo_license: null,-})--onMounted(() => {- form.email = user?.value?.email-})--const { invalidateAll: invalidateWorkspaces } = useWorkspaces()-const { invalidateAll: invalidateForms } = useForms()--const updateCredentials = () => {- loading.value = true- form- .post("update-credentials")- .then(async (_data) => {- useAuth().invalidateUser()- // Invalidate all workspace and form queries to refetch fresh data- await invalidateWorkspaces()- await invalidateForms()- router.push({ name: "home" })- })- .catch((error) => {- console.error(error)- useAlert().error(error.response._data.message)- })- .finally(() => {- loading.value = false- })-}--const logout = () => {- // Logout mutation handles cache clearing and navigation automatically- logoutMutation.mutateAsync()-}-</script>\ No newline at end of filediff --git a/client/plugins/feature-flags.client.js b/client/plugins/feature-flags.client.jsnew file mode 100644index 000000000..a4b349c54--- /dev/null+++ b/client/plugins/feature-flags.client.js@@ -0,0 +1,17 @@+export default defineNuxtPlugin((nuxtApp) => {+ // Access the same state that was set on server+ const featureFlagsState = useState('featureFlags', () => ({}))++ // Provide refresh capability+ nuxtApp.provide('refreshFeatureFlags', async () => {+ try {+ const { contentApi } = await import('~/api/content')+ const newFlags = await contentApi.featureFlags.list()+ featureFlagsState.value = newFlags+ return newFlags+ } catch (error) {+ console.error('Failed to refresh feature flags:', error)+ throw error+ }+ })+})\ No newline at end of filediff --git a/client/plugins/feature-flags.server.js b/client/plugins/feature-flags.server.jsnew file mode 100644index 000000000..9f67cc21d--- /dev/null+++ b/client/plugins/feature-flags.server.js@@ -0,0 +1,26 @@+export default defineNuxtPlugin(async (nuxtApp) => {+ // Load feature flags during SSR+ const featureFlagsState = useState('featureFlags', () => ({}))++ try {+ const { contentApi } = await import('~/api/content')+ const flags = await contentApi.featureFlags.list()+ featureFlagsState.value = flags+ } catch (error) {+ console.error('Failed to load feature flags on server:', error)+ // Keep empty object as fallback+ }++ // Provide refresh capability+ nuxtApp.provide('refreshFeatureFlags', async () => {+ try {+ const { contentApi } = await import('~/api/content')+ const newFlags = await contentApi.featureFlags.list()+ featureFlagsState.value = newFlags+ return newFlags+ } catch (error) {+ console.error('Failed to refresh feature flags:', error)+ throw error+ }+ })+})\ No newline at end of filediff --git a/client/plugins/featureFlags.js b/client/plugins/featureFlags.jsdeleted file mode 100644index 1bcc8b0c8..000000000--- a/client/plugins/featureFlags.js+++ /dev/null@@ -1,18 +0,0 @@-import { useFeatureFlagsStore } from '~/stores/featureFlags'--export default defineNuxtPlugin(async (nuxtApp) => {- // Get the pinia instance for SSR compatibility- const { $pinia } = nuxtApp-- try {- // Pass pinia instance for SSR compatibility- const featureFlagsStore = useFeatureFlagsStore($pinia)-- // Fetch flags during SSR to prevent hydration mismatches- if (!featureFlagsStore.isLoaded) {- await featureFlagsStore.fetchFlags()- }- } catch (error) {- console.error('Feature flags plugin failed:', error)- }-})\ No newline at end of filediff --git a/client/stores/featureFlags.js b/client/stores/featureFlags.jsdeleted file mode 100644index 9f57ea2f7..000000000--- a/client/stores/featureFlags.js+++ /dev/null@@ -1,28 +0,0 @@-import { defineStore } from 'pinia'-import { ref } from 'vue'--export const useFeatureFlagsStore = defineStore('feature_flags', () => {- const flags = ref({})- const isLoaded = ref(false)-- async function fetchFlags() {- if (isLoaded.value) return-- try {- const { data } = await useOpnApi('content/feature-flags')- flags.value = data.value- isLoaded.value = true- } catch (error) {- console.error('Failed to fetch feature flags:', error)- }- }-- function getFlag(path, defaultValue = false) {- return path.split('.').reduce((acc, part) => {- if (acc === undefined) return defaultValue- return acc && acc[part] !== undefined ? acc[part] : defaultValue- }, flags.value)- }-- return { flags, isLoaded, fetchFlags, getFlag }-})\ No newline at end of filediff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 08b67dd0f..4e045bb21 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -9,9 +9,16 @@ services:- /usr/share/nginx/html/vendor # Exclude vendor directory from the mount- ./api/storage:/usr/share/nginx/html/storage:delegatedenvironment:+ # Core Laravel settingsAPP_ENV: local- APP_DEBUG: true- APP_DEV_CORS: true+ APP_DEBUG: "true"+ APP_DEV_CORS: "true"+ APP_URL: http://localhost+ FRONT_URL: http://localhost:3000+ APP_KEY: base64:dD8AFEB45nKZ0VWmIPiW495rDYb+ywRJnCCSdycw0pI=+ JWT_SECRET: 38hjE96gYu4ceKSSHNnzgeynMr2m3WkNBN2u7zzpVeiITtxFEloxAjcr7TCKuiiy+ # Self-hosted configuration+ SELF_HOSTED: "true"# Database settingsDB_HOST: dbDB_DATABASE: ${DB_DATABASE:-forge}@@ -25,6 +32,10 @@ services:# Storage settingsFILESYSTEM_DISK: localLOCAL_FILESYSTEM_VISIBILITY: public+ # Mail settings (development - uses log driver)+ MAIL_MAILER: log+ MAIL_FROM_ADDRESS: dev@localhost+ MAIL_FROM_NAME: OpnForm-Dev# PHP ConfigurationPHP_MEMORY_LIMIT: "1G"PHP_MAX_EXECUTION_TIME: "600"@@ -34,8 +45,6 @@ services:PHP_IDE_CONFIG: serverName=DockerXDEBUG_MODE: ${XDEBUG_MODE:-off}XDEBUG_CONFIG: client_host=host.docker.internal- APP_URL: http://localhost- FRONT_URL: http://localhost:3000depends_on:db:condition: service_healthy@@ -43,28 +52,27 @@ services:ui:image: jhumanj/opnform-client:devcontainer_name: opnform-client- command: sh -c "npm install && NITRO_HOST=0.0.0.0 NITRO_PORT=3000 npm run dev"+ command: sh -c "+ if [ ! -f node_modules/.install-complete ] || [ package.json -nt node_modules/.install-complete ]; then+ echo 'Installing dependencies...';+ npm install && touch node_modules/.install-complete;+ else+ echo 'Dependencies up to date, skipping install';+ fi && npm run docker-dev"volumes:- ./client:/app:delegated- - /app/node_modules # Keep container's node_modules+ - client_node_modules:/app/node_modules # Named volume for persistenceenvironment:NODE_ENV: developmentNUXT_PUBLIC_APP_ENV: development- HOST: "0.0.0.0"- PORT: 3000- # HMR settings- CHOKIDAR_USEPOLLING: "true"- WATCHPACK_POLLING: "true"- VITE_HMR_HOST: "localhost"- VITE_HMR_PORT: 24678- # API settings- NUXT_PUBLIC_APP_URL_BASE: "http://localhost"- NUXT_PUBLIC_API_BASE: "http://localhost/api"+ NUXT_PUBLIC_APP_URL: "http://localhost:3000"+ NUXT_PUBLIC_API_BASE: "http://localhost"+ NUXT_PRIVATE_API_BASE: "http://opnform-ingress"extra_hosts:- "host.docker.internal:host-gateway"ports:- - "3000:3000" # Main dev server- - "24678:24678" # Vite HMR port+ - "3000:3000" # Main dev server+ - "24678:24678" # Vite HMR portdb:image: postgres:16@@ -101,4 +109,5 @@ services:condition: service_startedvolumes:- postgres-data:\ No newline at end of file+ postgres-data:+ client_node_modules:diff --git a/docker-compose.yml b/docker-compose.ymlindex c1ca24382..a50cc5ea0 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -41,7 +41,8 @@ services:<<: *api-envAPP_ENV: productionhealthcheck:- test: ["CMD-SHELL", "pgrep -f 'php artisan queue:work' > /dev/null || exit 1"]+ test:+ ["CMD-SHELL", "pgrep -f 'php artisan queue:work' > /dev/null || exit 1"]interval: 60stimeout: 10sretries: 3@@ -55,7 +56,11 @@ services:<<: *api-envAPP_ENV: productionhealthcheck:- test: ["CMD-SHELL", "php /usr/share/nginx/html/artisan app:scheduler-status --mode=check --max-minutes=3 || exit 1"]+ test:+ [+ "CMD-SHELL",+ "php /usr/share/nginx/html/artisan app:scheduler-status --mode=check --max-minutes=3 || exit 1",+ ]interval: 60stimeout: 30sretries: 3@@ -67,7 +72,8 @@ services:env_file:- ./client/.envhealthcheck:- test: ["CMD-SHELL", "wget --spider -q http://localhost:3000/login || exit 1"]+ test:+ ["CMD-SHELL", "wget --spider -q http://localhost:3000/login || exit 1"]interval: 30stimeout: 10sretries: 3@@ -76,6 +82,8 @@ services:redis:image: redis:7container_name: opnform-redis+ volumes:+ - redis-data:/datahealthcheck:test: ["CMD-SHELL", "redis-cli ping | grep PONG"]interval: 30s@@ -118,4 +126,5 @@ services:volumes:postgres-data:- opnform_storage:\ No newline at end of file+ opnform_storage:+ redis-data:diff --git a/docker/Dockerfile.api b/docker/Dockerfile.apiindex a3e5b9ec5..c4976b024 100644--- a/docker/Dockerfile.api+++ b/docker/Dockerfile.api@@ -78,7 +78,7 @@ RUN mkdir -p storage/framework/sessions \# Copy the entire application from the builder stageCOPY --from=builder /app/ ./-# Set version as environment variable (more reliable than file approach)+# Set version as environment variableENV APP_VERSION_DOCKER=$APP_VERSION# Setup entrypointdiff --git a/docker/Dockerfile.client b/docker/Dockerfile.clientindex 80b262621..84dd0c2c2 100644--- a/docker/Dockerfile.client+++ b/docker/Dockerfile.client@@ -1,4 +1,4 @@-FROM node:20-alpine AS javascript-builder+FROM node:24-alpine AS javascript-builderWORKDIR /app# It's best to add as few files as possible before running the build commands@@ -16,21 +16,30 @@ RUN npm cache clean --force && \rm -rf node_modules && \npm ci+# Clean up after npm install to free memory+RUN npm cache clean --force+# Explicitly install the correct version of esbuild# RUN npm install [email protected]ADD ./client/ /app/-# Optimize memory usage during build-ENV NODE_OPTIONS="--max-old-space-size=4096"+ENV NODE_OPTIONS="--max-old-space-size=6144"# Set production mode to reduce memory usageENV NODE_ENV=production# Disable source maps to reduce memory usageENV GENERATE_SOURCEMAP=false-# Run the build-RUN npm run build--FROM node:20-alpine+# Additional memory optimizations+ENV NUXT_TELEMETRY_DISABLED=1+# Optimize Vite build for memory+ENV VITE_NODE_OPTIONS="--max-old-space-size=10240"+# Run the build with additional memory optimizations and limited concurrency+RUN --mount=type=tmpfs,target=/tmp \+ NODE_OPTIONS="--max-old-space-size=10240" \+ NUXT_BUILD_CONCURRENCY=1 \+ npm run build++FROM node:24-alpineWORKDIR /appCOPY --from=javascript-builder /app/.output/ /app/RUN ls /app/diff --git a/docker/nginx.dev.conf b/docker/nginx.dev.confindex 38202a14c..f33a9ccd0 100644--- a/docker/nginx.dev.conf+++ b/docker/nginx.dev.conf@@ -1,8 +1,3 @@-map $original_uri $api_uri {- ~^/api(/.*$) $1;- default $original_uri;-}-server {listen 80;server_name localhost;@@ -14,43 +9,26 @@ server {index index.html index.htm index.php;- # Frontend proxy- location / {- proxy_http_version 1.1;- proxy_pass http://ui:3000;- proxy_set_header Host $host;- proxy_set_header X-Real-IP $remote_addr;- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;- proxy_set_header X-Forwarded-Proto $scheme;- proxy_set_header X-Forwarded-Host $host;- proxy_set_header X-Forwarded-Port $server_port;- proxy_set_header Upgrade $http_upgrade;- proxy_set_header Connection "Upgrade";+ # Handle static files directly+ location ~* \.(css|js|ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$ {+ expires 1y;+ add_header Cache-Control "public, immutable";+ try_files $uri =404;}- # HMR websocket support- location /_nuxt {- proxy_pass http://ui:3000;- proxy_http_version 1.1;- proxy_set_header Host $host;- proxy_set_header Upgrade $http_upgrade;- proxy_set_header Connection "upgrade";- proxy_cache_bypass $http_upgrade;- }-- # API handling- location ~/(api|open|local\/temp|forms\/assets)/ {- set $original_uri $uri;+ # Handle API routes and other backend paths+ location / {try_files $uri $uri/ /index.php$is_args$args;}+ # PHP-FPM processinglocation ~ \.php$ {fastcgi_split_path_info ^(.+\.php)(/.+)$;fastcgi_pass api:9000;fastcgi_index index.php;include fastcgi_params;- fastcgi_param SCRIPT_FILENAME $document_root/index.php;- fastcgi_param REQUEST_URI $api_uri;+ fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;+ fastcgi_param PATH_INFO $fastcgi_path_info;fastcgi_read_timeout 300;}diff --git a/docker/php-fpm-entrypoint b/docker/php-fpm-entrypointindex 4fc7e7ffb..e25ca9da5 100644--- a/docker/php-fpm-entrypoint+++ b/docker/php-fpm-entrypoint@@ -27,7 +27,6 @@ main() {if [ "$ROLE" = "api" ]; thenecho "Running setup for API role..."apply_db_migrations- run_init_projectoptimize_applicationecho "Starting server for API role with command: $@"exec "$@"@@ -125,11 +124,6 @@ apply_db_migrations() {php ./artisan migrate --force}-run_init_project() {- echo "Running app:init-project command"- php ./artisan app:init-project-}-optimize_application() {echo "Clearing application cache"php ./artisan optimize:cleardiff --git a/docs/deployment/docker-development.mdx b/docs/deployment/docker-development.mdxindex 37650aa12..e36892b18 100644--- a/docs/deployment/docker-development.mdx+++ b/docs/deployment/docker-development.mdx@@ -5,7 +5,7 @@ description: "Set up OpnForm locally for development using Docker"import CloudVersion from "/snippets/cloud-version.mdx";-<CloudVersion/>+<CloudVersion />## Overview@@ -13,97 +13,141 @@ OpnForm provides a minimal Docker-based development environment optimized for lo## Prerequisites-- Docker and Docker Compose installed on your machine-- Git installed-- Basic understanding of Docker concepts+- Docker and Docker Compose installed on your machine+- Git installed+- Basic understanding of Docker concepts## Quick Start1. Clone the repository:- ```bash- git clone https://github.com/JhumanJ/OpnForm.git- cd OpnForm- ```++ ```bash+ git clone https://github.com/JhumanJ/OpnForm.git+ cd OpnForm+ ```2. Run the setup script in development mode:- ```bash- chmod +x scripts/docker-setup.sh- ./scripts/docker-setup.sh --dev- ```- This script will:- - Create necessary environment files- - Pull or build required Docker images- - Start all containers in development mode- - Display access information+ ```bash+ chmod +x scripts/docker-setup.sh+ ./scripts/docker-setup.sh --dev+ ```-3. Access your development environment:- - Frontend: http://localhost:3000- - API: http://localhost/api+ This script will:++ - Pull or build required Docker images+ - Start all containers in development mode with embedded configuration+ - Display access information-### Initial Login+ <Note>+ Development mode doesn't require .env files - all configuration is+ embedded in docker-compose.dev.yml for simplicity.+ </Note>-After starting the development environment, use these credentials to access the app:+3. Access your development environment:+ - **Frontend**: http://localhost:3000 (direct access to Nuxt dev server)+ - **API**: http://localhost/api (proxied through nginx)-- Email: `[email protected]`-- Password: `password`+### Initial Setup-You will be prompted to change your email and password after your first login.+After starting the development environment, OpnForm will automatically redirect you to a setup page where you can create your admin account. Simply visit `http://localhost:3000/setup` and you'll be guided through the setup process.-<Note>Public registration is disabled in the self-hosted version. Use the admin account to invite additional users.</Note>+<Note>+ Public registration is disabled in the self-hosted version after setup is+ complete. Use the admin account to invite additional users.+</Note>## Architecture-While the full architecture is detailed in our [Docker Deployment](/deployment/docker) guide, the development setup is intentionally lighter and focused on developer experience.+The development setup is intentionally simplified compared to our [Docker Deployment](/deployment/docker) production setup, with a focus on developer experience and faster iteration.++### Key Simplifications++- **No .env Files**: All configuration embedded in docker-compose.dev.yml - no environment file generation needed+- **Direct Frontend Access**: Frontend runs on port 3000 with direct access, bypassing nginx proxy+- **Lightweight nginx**: Only handles API routes and Laravel backend, eliminating redundant frontend proxying+- **Simplified networking**: Fewer moving parts, cleaner logs, easier debugging### Differences from Production-- **No Redis**: Uses file-based caching and sessions instead- - Simpler setup- - No additional service to maintain- - Slightly slower but sufficient for development+- **No Redis**: Uses file-based caching and sessions instead++ - Simpler setup+ - No additional service to maintain+ - Slightly slower but sufficient for development++- **No Queue Workers**: Uses synchronous job processing++ - Jobs run immediately in the main process+ - Easier debugging of background tasks+ - No need to restart workers after code changes++- **No Scheduler**: Scheduled tasks don't run automatically++ - Run scheduled tasks manually when needed+ - Less resource usage+ - Cleaner logs-- **No Queue Workers**: Uses synchronous job processing- - Jobs run immediately in the main process- - Easier debugging of background tasks- - No need to restart workers after code changes+- **Embedded Configuration**: No `.env` files needed-- **No Scheduler**: Scheduled tasks don't run automatically- - Run scheduled tasks manually when needed- - Less resource usage- - Cleaner logs+ - All variables set directly in docker-compose.dev.yml+ - Includes secure development keys (APP_KEY, JWT_SECRET)+ - Pre-configured mail settings using log driver+ - Immediate startup without setup scripts### Development FeaturesThe development setup includes:#### Frontend Development-- **Hot Module Replacement (HMR)**: Changes to Vue components and styles are instantly reflected without page reload-- **Vue DevTools**: Full integration for component inspection and state management debugging ([learn more](https://devtools.vuejs.org/))-- **Source Maps**: Enabled for easier debugging-- **Fast Refresh**: Preserves component state during updates-- **Error Overlay**: Displays errors directly in the browser++- **Hot Module Replacement (HMR)**: Changes to Vue components and styles are instantly reflected without page reload+- **Vue DevTools**: Full integration for component inspection and state management debugging ([learn more](https://devtools.vuejs.org/))+- **Source Maps**: Enabled for easier debugging+- **Fast Refresh**: Preserves component state during updates+- **Error Overlay**: Displays errors directly in the browser#### Backend Development-- **PHP Hot Reload**: Changes to PHP files are immediately available-- **Xdebug Integration**: Ready for step-by-step debugging-- **Artisan Commands**: Direct access to Laravel's CLI tools++- **PHP Hot Reload**: Changes to PHP files are immediately available+- **Xdebug Integration**: Ready for step-by-step debugging+- **Artisan Commands**: Direct access to Laravel's CLI tools++#### Performance Optimizations++The development setup includes smart optimizations for faster iteration:++- **Smart Dependency Install**: Automatically detects when `package.json` has changed and only reinstalls when necessary+ - First startup: Full npm install (2-3 minutes)+ - Subsequent startups: "Dependencies up to date, skipping install" (5 seconds)+ - Automatic detection when dependencies change+- **Persistent Node Modules**: Dependencies stored in Docker volumes to avoid reinstallation+- **Fast Container Restarts**: Skip dependency installation on container restart### Development URLs-- **Frontend**: http://localhost:3000- - Direct access to Nuxt dev server- - Includes HMR websocket connection- - Vue DevTools available+- **Frontend**: http://localhost:3000-- **API**: http://localhost/api- - Handled by Nginx reverse proxy- - Automatic routing to PHP-FPM- - Supports file uploads and long requests+ - Direct access to Nuxt dev server with HMR+ - Vue DevTools available+ - All client-side routing handled directly++- **API**: http://localhost/api+ - Lightweight nginx proxy to Laravel API+ - Routes all backend requests through Laravel's front controller+ - PHP-FPM processing for server-side logic+ - Supports file uploads and long requests++<Note>+ In development, nginx handles all Laravel routes (including `/`, `/api/*`,+ `/forms/*`) through the standard Laravel front controller pattern. The+ frontend is accessed directly on port 3000, eliminating redundant proxying.+</Note>## File StructureThe development setup mounts your local directories into the containers:+```OpnForm/βββ api/ # Laravel API (mounted to api container)@@ -146,28 +190,70 @@ docker compose -f docker-compose.dev.yml logs -f ui### Database AccessThe PostgreSQL database is accessible:-- From containers: `host=db`-- From your machine: `localhost:5432`-- Default credentials:- ```- Host: localhost- Port: 5432- Database: forge- Username: forge- Password: forge- ```++- From containers: `host=db`+- From your machine: `localhost:5432`+- Default credentials:+ ```+ Host: localhost+ Port: 5432+ Database: forge+ Username: forge+ Password: forge+ ```## Troubleshooting### Container Issues+If containers aren't starting properly:+```bash# Clean everything and restart./scripts/docker-setup.sh --dev```+### Frontend Access Issues++If you get **503 errors** when accessing the frontend:++<Steps>+<Step title="Use IPv4 address">+ Always use `http://127.0.0.1:3000` instead of `http://localhost:3000`++ <Warning>+ `localhost` can resolve to IPv6 (`::1`) on some systems, causing connection issues with Docker's port binding.+ </Warning>+</Step>++<Step title="Check container logs">+ Verify the Nuxt dev server started successfully: ```bash docker compose -f+ docker-compose.dev.yml logs ui ``` Look for: `"Dependencies up to date,+ skipping install"` and `"β Local: http://0.0.0.0:3000/"`+</Step>++<Step title="Restart containers if needed">+ ```bash+ docker compose -f docker-compose.dev.yml restart ui+ ```+</Step>+</Steps>++### Environment Variables++Development mode uses embedded configuration - no `.env` files needed:++- **APP_KEY** and **JWT_SECRET**: Pre-configured development keys+- **Database**: Defaults to `forge/forge` credentials+- **Mail**: Uses log driver for development+- **Storage**: Local filesystem with public visibility++To customize variables, edit them directly in `docker-compose.dev.yml`.+### Permission Issues+If you encounter permission issues:+```bash# Fix storage permissionsdocker compose -f docker-compose.dev.yml exec api chmod -R 775 storage@@ -177,14 +263,34 @@ docker compose -f docker-compose.dev.yml exec api chmod -R 775 vendor```### HMR Issues+If hot reload isn't working:+1. Check browser console for WebSocket errors2. Ensure ports 3000 and 24678 are available3. Try restarting the UI container:- ```bash- docker compose -f docker-compose.dev.yml restart ui- ```+ ```bash+ docker compose -f docker-compose.dev.yml restart ui+ ```++### Dependency Installation Issues++If you need to force reinstall dependencies:++```bash+# Remove the install marker to force reinstall+docker compose -f docker-compose.dev.yml exec ui rm -f node_modules/.install-complete++# Or clear the entire volume+docker volume rm opnform_client_node_modules+```## Environment Variables-For detailed information about environment variables and how to update them in Docker, see our [Environment Variables](/configuration/environment-variables#docker-environment-variables) documentation.\ No newline at end of file+For production deployments, see our [Environment Variables](/configuration/environment-variables#docker-environment-variables) documentation.++<Note>+ Development mode doesn't use `.env` files. All configuration is embedded in+ `docker-compose.dev.yml` for simplicity. To modify variables, edit the+ `environment:` section directly in that file.+</Note>diff --git a/docs/deployment/docker.mdx b/docs/deployment/docker.mdxindex 3059441e0..3ad5dcccb 100644--- a/docs/deployment/docker.mdx+++ b/docs/deployment/docker.mdx@@ -5,57 +5,55 @@ description: "Deploy OpnForm using Docker"import CloudVersion from "/snippets/cloud-version.mdx";-<CloudVersion/>+<CloudVersion /><Tip>-Looking to develop OpnForm locally? Check out our [Docker Development Setup](/deployment/docker-development) guide which provides hot-reload and other development features.+ Looking to develop OpnForm locally? Check out our [Docker Development+ Setup](/deployment/docker-development) guide which provides hot-reload and+ other development features.</Tip>## Quick Start1. Clone the repository:- ```bash- git clone https://github.com/JhumanJ/OpnForm.git- cd OpnForm- ```+ ```bash+ git clone https://github.com/JhumanJ/OpnForm.git+ cd OpnForm+ ```<Warning>-**Important for Windows Users**: Ensure script files maintain LF (Unix-style) line endings. If you're using Windows, configure Git to preserve line endings:-```bash-git config core.autocrlf false-```-And check/fix the artisan script before running setup:-```bash-# Using Git Bash or WSL-dos2unix api/artisan-```-Otherwise, Docker containers may hang at "Waiting for DB to be ready" during startup.+ **Important for Windows Users**: Ensure script files maintain LF+ (Unix-style) line endings. If you're using Windows, configure Git to+ preserve line endings: ```bash git config core.autocrlf false ``` And+ check/fix the artisan script before running setup: ```bash # Using Git Bash+ or WSL dos2unix api/artisan ``` Otherwise, Docker containers may hang at+ "Waiting for DB to be ready" during startup.</Warning>2. Run the setup script:- ```bash- chmod +x scripts/docker-setup.sh- ./scripts/docker-setup.sh- ```- The script will:- - Create necessary environment files- - Pull required Docker images- - Start all containers in production mode- - Display access information+ ```bash+ chmod +x scripts/docker-setup.sh+ ./scripts/docker-setup.sh+ ```-3. Access your OpnForm instance at `http://localhost`+ The script will:-### Initial Login+ - Create necessary environment files+ - Pull required Docker images+ - Start all containers in production mode+ - Display access information-After deployment, use these credentials to access the app:+3. Access your OpnForm instance at `http://localhost`-- Email: `[email protected]`-- Password: `password`+### Initial Setup-You will be prompted to change your email and password after your first login.+After deployment, OpnForm will automatically redirect you to a setup page where you can create your admin account. Simply visit `http://localhost` and you'll be guided through the setup process.-<Note>Public registration is disabled in the self-hosted version. Use the admin account to invite additional users.</Note>+<Note>+ Public registration is disabled in the self-hosted version after setup is+ complete. Use the admin account to invite additional users.+</Note>## Architecture@@ -72,52 +70,40 @@ graph TD### Components<Tabs>- <Tab title="Frontend">- The Nuxt frontend service:- - Server-Side Rendered application- - Built with Vue 3 and Tailwind CSS- - Handles dynamic rendering and client-side interactivity- - Optimized for production performance- </Tab>- <Tab title="Backend">- The Laravel API service:- - Handles business logic and data persistence- - Provides REST API endpoints- - Manages file uploads and processing- - Includes required PHP extensions (pgsql, redis, etc.)- - Configured for PostgreSQL and Redis connections- </Tab>- <Tab title="Workers">- Background processing services:- - **API Worker**: Processes queued jobs (emails, exports, etc.)- - **API Scheduler**: Handles scheduled tasks and periodic cleanups- - Both share the same codebase as the main API- </Tab>- <Tab title="Databases">- Data storage services:- - **PostgreSQL**: Primary database for all application data- - **Redis**: Used for:- - Session storage- - Cache- - Queue management- - Real-time features- </Tab>- <Tab title="Proxy">- The Nginx proxy service:- - Routes requests between frontend and backend- - Handles SSL termination- - Manages file upload limits- - Serves static assets- - Configured for optimal performance- </Tab>+ <Tab title="Frontend">+ The Nuxt frontend service: - Server-Side Rendered application - Built+ with Vue 3 and Tailwind CSS - Handles dynamic rendering and client-side+ interactivity - Optimized for production performance+ </Tab>+ <Tab title="Backend">+ The Laravel API service: - Handles business logic and data persistence -+ Provides REST API endpoints - Manages file uploads and processing -+ Includes required PHP extensions (pgsql, redis, etc.) - Configured for+ PostgreSQL and Redis connections+ </Tab>+ <Tab title="Workers">+ Background processing services: - **API Worker**: Processes queued jobs+ (emails, exports, etc.) - **API Scheduler**: Handles scheduled tasks and+ periodic cleanups - Both share the same codebase as the main API+ </Tab>+ <Tab title="Databases">+ Data storage services: - **PostgreSQL**: Primary database for all+ application data - **Redis**: Used for: - Session storage - Cache -+ Queue management - Real-time features+ </Tab>+ <Tab title="Proxy">+ The Nginx proxy service: - Routes requests between frontend and backend+ - Handles SSL termination - Manages file upload limits - Serves static+ assets - Configured for optimal performance+ </Tab></Tabs>## Docker ImagesOpnForm provides pre-built Docker images for easy deployment:-- [OpnForm API Image](https://hub.docker.com/r/jhumanj/opnform-api)-- [OpnForm Client Image](https://hub.docker.com/r/jhumanj/opnform-client)+- [OpnForm API Image](https://hub.docker.com/r/jhumanj/opnform-api)+- [OpnForm Client Image](https://hub.docker.com/r/jhumanj/opnform-client)### Building Custom Images@@ -133,19 +119,20 @@ docker build -t opnform-ui:local -f docker/Dockerfile.client .```### Custom Configuration+Create a `docker-compose.override.yml` to customize your deployment:```yamlservices:- api:- image: opnform-api:local- environment:- PHP_MEMORY_LIMIT: 1G- ui:- image: opnform-ui:local- ingress:- volumes:- - ./custom-nginx.conf:/etc/nginx/conf.d/default.conf+ api:+ image: opnform-api:local+ environment:+ PHP_MEMORY_LIMIT: 1G+ ui:+ image: opnform-ui:local+ ingress:+ volumes:+ - ./custom-nginx.conf:/etc/nginx/conf.d/default.conf```## Environment Variables@@ -157,19 +144,21 @@ For detailed information about environment variables and how to update them in D### Updates1. Pull latest changes:- ```bash- git pull origin main- ```++ ```bash+ git pull origin main+ ```2. Update containers:- ```bash- docker compose pull- docker compose up -d- ```+ ```bash+ docker compose pull+ docker compose up -d+ ```### MonitoringView container logs:+```bash# All containersdocker compose logs -f@@ -179,6 +168,7 @@ docker compose logs -f api```Monitor container health:+```bashdocker compose ps```@@ -188,6 +178,7 @@ docker compose ps### Container IssuesIf containers aren't starting:+```bash# View detailed logsdocker compose logs -f@@ -200,6 +191,7 @@ docker compose up -d### Database IssuesIf database connections fail:+```bash# Check database statusdocker compose exec db pg_isready@@ -209,6 +201,7 @@ docker compose logs db```If the API container is stuck on "Waiting for DB to be ready":+```bash# Check for line ending issues in the artisan script# The file should use LF (Unix) line endings, not CRLF (Windows)@@ -221,12 +214,17 @@ dos2unix api/artisan```<Note>-**Line Ending Issue**: When using Git or code editors on Windows, line endings in the `artisan` script may be converted from LF (Unix-style) to CRLF (Windows-style). This prevents the Docker container from properly executing the script, causing it to hang at "Waiting for DB to be ready". Always ensure script files maintain LF line endings.+ **Line Ending Issue**: When using Git or code editors on Windows, line+ endings in the `artisan` script may be converted from LF (Unix-style) to+ CRLF (Windows-style). This prevents the Docker container from properly+ executing the script, causing it to hang at "Waiting for DB to be ready".+ Always ensure script files maintain LF line endings.</Note>### Cache IssuesClear various caches:+```bash# Clear application cachedocker compose exec api php artisan cache:clear@@ -241,6 +239,7 @@ docker compose exec api php artisan route:clear### Permission IssuesFix storage permissions:+```bashdocker compose exec api chown -R www-data:www-data storagedocker compose exec api chmod -R 775 storagediff --git a/scripts/docker-setup.sh b/scripts/docker-setup.shindex 1f3b765f1..7bbeed4e4 100755--- a/scripts/docker-setup.sh+++ b/scripts/docker-setup.sh@@ -38,9 +38,13 @@ cd "$PROJECT_ROOT"echo -e "${BLUE}Starting OpnForm Docker setup...${NC}"-# Run the environment setup script with --docker flag-echo -e "${GREEN}Setting up environment files...${NC}"-bash "$SCRIPT_DIR/setup-env.sh" --docker+# Run the environment setup script with --docker flag (only for production)+if [ "$DEV_MODE" = false ]; then+ echo -e "${GREEN}Setting up environment files...${NC}"+ bash "$SCRIPT_DIR/setup-env.sh" --docker+else+ echo -e "${GREEN}Development mode - skipping .env generation (using docker-compose environment variables)${NC}"+fi# Determine which compose file to useif [ "$DEV_MODE" = true ]; then@@ -51,21 +55,24 @@ elseCOMPOSE_FILE="docker-compose.yml"fi+# Check for override file and build compose command+COMPOSE_CMD="docker compose -f $COMPOSE_FILE"+if [ -f "docker-compose.override.yml" ]; then+ echo -e "${BLUE}Found docker-compose.override.yml - including local overrides${NC}"+ COMPOSE_CMD="$COMPOSE_CMD -f docker-compose.override.yml"+fi+# Start Docker containersecho -e "${GREEN}Starting Docker containers...${NC}"-docker compose -f $COMPOSE_FILE up -d+$COMPOSE_CMD up -d# Display access instructionsif [ "$DEV_MODE" = true ]; thenecho -e "${BLUE}Development environment setup complete!${NC}"echo -e "${YELLOW}Please wait for the frontend to finish building (this may take a few minutes)${NC}"- echo -e "${GREEN}Then visit: http://localhost:3000${NC}"+ echo -e "${GREEN}Then visit: http://localhost:3000/setup${NC}"elseecho -e "${BLUE}Production environment setup complete!${NC}"echo -e "${YELLOW}Please wait a moment for all services to start${NC}"echo -e "${GREEN}Then visit: http://localhost${NC}"fi--echo -e "${BLUE}Default admin credentials:${NC}"-echo -e "${GREEN}Email: [email protected]${NC}"-echo -e "${GREEN}Password: password${NC}"