start-vibing-stacks 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,16 +5,16 @@
5
5
  - **ReactJS >= 19** — MANDATORY
6
6
  - **TailwindCSS >= 4** — MANDATORY
7
7
 
8
- ## Translation Pattern
8
+ ## Label Constants Pattern
9
9
 
10
10
  ```tsx
11
- // ✅ Translations as CONST at the top, BEFORE hooks
11
+ // ✅ Labels as CONST at the top, BEFORE hooks
12
12
  const LABELS = {
13
- title: __('dashboard.title'),
14
- save: __('common.save'),
15
- cancel: __('common.cancel'),
16
- errorRequired: __('errors.field_required'),
17
- };
13
+ title: 'Dashboard',
14
+ save: 'Save',
15
+ cancel: 'Cancel',
16
+ errorRequired: 'This field is required',
17
+ } as const;
18
18
 
19
19
  export default function Dashboard() {
20
20
  const [data, setData] = useState(null);
@@ -22,14 +22,14 @@ export default function Dashboard() {
22
22
  return <h1>{LABELS.title}</h1>;
23
23
  }
24
24
 
25
- // ❌ NEVER call __() inside JSX (Hook violations)
26
- return <h1>{__('dashboard.title')}</h1>; // ❌
25
+ // ❌ NEVER scatter string literals across JSX
26
+ return <h1>Dashboard</h1>; // ❌ Duplicated, hard to maintain
27
27
  ```
28
28
 
29
29
  **Rules:**
30
- - Translations in `CONST` variables before state hooks
31
- - New strings add to `lang/en/*.php` and `lang/pt/*.php`
32
- - Error strings centralized in `lang/*/errors.php`
30
+ - Labels in `CONST` objects before state hooks for stable references
31
+ - For i18n projects, use `next-intl` or `i18next` same CONST pattern applies with `t()` calls
32
+ - Error strings centralized in a shared constants file
33
33
 
34
34
  ## Debug Logging
35
35
 
@@ -65,11 +65,11 @@ export default function Dashboard() {
65
65
 
66
66
  ```tsx
67
67
  // ═══════════════════════════════════════════
68
- // 1. TRANSLATIONS (before hooks)
68
+ // 1. LABELS (before hooks)
69
69
  // ═══════════════════════════════════════════
70
70
  const LABELS = {
71
- title: __('dashboard.title'),
72
- save: __('common.save'),
71
+ title: 'Dashboard',
72
+ save: 'Save',
73
73
  } as const;
74
74
 
75
75
  // ═══════════════════════════════════════════
@@ -156,7 +156,7 @@ import { cn } from '@/lib/utils';
156
156
  5. **Shared styles** — create a `styles.ts` file for cross-component constants
157
157
 
158
158
  ```tsx
159
- // resources/js/styles.ts — shared across components
159
+ // src/styles.ts — shared across components
160
160
  export const SHARED_STYLES = {
161
161
  page: 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8',
162
162
  btnPrimary: 'px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary-hover ...',
@@ -187,10 +187,10 @@ export default function Bad() {
187
187
  ## SVG Icons
188
188
 
189
189
  ```tsx
190
- // ✅ Separate files, import with ?react
191
- // resources/js/Icons/CheckIcon.svg
192
- import CheckIcon from '@/Icons/CheckIcon.svg?react';
193
- import { CheckIcon, AlertIcon } from '@/Icons';
190
+ // ✅ Separate files, import with ?react (Vite) or as components
191
+ // src/components/icons/CheckIcon.svg
192
+ import CheckIcon from '@/components/icons/CheckIcon.svg?react';
193
+ import { CheckIcon, AlertIcon } from '@/components/icons';
194
194
 
195
195
  // ❌ Inline SVG
196
196
  <svg viewBox="0 0 24 24">...</svg> // ❌ Bloats JSX
@@ -138,7 +138,7 @@ function UserList({ users }: { users: User[] }) {
138
138
  icon={<Users className="h-8 w-8" />}
139
139
  title="No users yet"
140
140
  description="Invite your first team member"
141
- action={{ label: 'Invite User', onClick: () => router.visit('/users/invite') }}
141
+ action={{ label: 'Invite User', onClick: () => window.location.assign('/users/invite') }}
142
142
  />
143
143
  );
144
144
  }
@@ -191,57 +191,76 @@ function EmptyState({ icon, title, description, action }: {
191
191
  </button>
192
192
  ```
193
193
 
194
- ## Form Pattern (Inertia.js)
194
+ ## Form Pattern (React Hook Form + Zod)
195
195
 
196
196
  ```tsx
197
- import { useForm } from '@inertiajs/react';
197
+ import { useForm } from 'react-hook-form';
198
+ import { zodResolver } from '@hookform/resolvers/zod';
199
+ import { useMutation } from '@tanstack/react-query';
200
+ import { z } from 'zod';
201
+ import { toast } from 'sonner';
202
+
203
+ const CreateUserSchema = z.object({
204
+ name: z.string().min(2, 'Name is required'),
205
+ email: z.string().email('Invalid email'),
206
+ });
207
+
208
+ type CreateUserForm = z.infer<typeof CreateUserSchema>;
198
209
 
199
210
  export default function CreateUser() {
200
- const { data, setData, post, processing, errors, reset } = useForm({
201
- name: '',
202
- email: '',
211
+ const {
212
+ register,
213
+ handleSubmit,
214
+ reset,
215
+ formState: { errors },
216
+ } = useForm<CreateUserForm>({
217
+ resolver: zodResolver(CreateUserSchema),
203
218
  });
204
219
 
205
- const submit = (e: React.FormEvent) => {
206
- e.preventDefault();
207
- post('/users', {
208
- onSuccess: () => {
209
- toast.success('User created!');
210
- reset();
211
- },
212
- onError: () => toast.error('Failed to create user'),
213
- });
214
- };
220
+ const mutation = useMutation({
221
+ mutationFn: (data: CreateUserForm) =>
222
+ fetch('/api/users', {
223
+ method: 'POST',
224
+ headers: { 'Content-Type': 'application/json' },
225
+ body: JSON.stringify(data),
226
+ }).then((res) => {
227
+ if (!res.ok) throw new Error('Failed to create user');
228
+ return res.json();
229
+ }),
230
+ onSuccess: () => {
231
+ toast.success('User created!');
232
+ reset();
233
+ },
234
+ onError: () => toast.error('Failed to create user'),
235
+ });
215
236
 
216
237
  return (
217
- <form onSubmit={submit} className="space-y-4">
238
+ <form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-4">
218
239
  <div>
219
240
  <label className="block text-sm font-medium text-foreground mb-1">Name</label>
220
241
  <input
221
- value={data.name}
222
- onChange={e => setData('name', e.target.value)}
242
+ {...register('name')}
223
243
  className="w-full h-10 px-3 rounded-md border border-border bg-background text-foreground"
224
244
  />
225
- {errors.name && <p className="mt-1 text-sm text-destructive">{errors.name}</p>}
245
+ {errors.name && <p className="mt-1 text-sm text-destructive">{errors.name.message}</p>}
226
246
  </div>
227
247
 
228
248
  <div>
229
249
  <label className="block text-sm font-medium text-foreground mb-1">Email</label>
230
250
  <input
231
251
  type="email"
232
- value={data.email}
233
- onChange={e => setData('email', e.target.value)}
252
+ {...register('email')}
234
253
  className="w-full h-10 px-3 rounded-md border border-border bg-background text-foreground"
235
254
  />
236
- {errors.email && <p className="mt-1 text-sm text-destructive">{errors.email}</p>}
255
+ {errors.email && <p className="mt-1 text-sm text-destructive">{errors.email.message}</p>}
237
256
  </div>
238
257
 
239
258
  <button
240
259
  type="submit"
241
- disabled={processing}
260
+ disabled={mutation.isPending}
242
261
  className="bg-primary text-primary-foreground px-6 py-2 rounded-lg hover:bg-primary-hover disabled:opacity-50 transition-colors"
243
262
  >
244
- {processing ? (
263
+ {mutation.isPending ? (
245
264
  <span className="flex items-center gap-2">
246
265
  <Loader className="h-4 w-4 animate-spin" /> Creating...
247
266
  </span>
@@ -252,27 +271,44 @@ export default function CreateUser() {
252
271
  }
253
272
  ```
254
273
 
255
- ## Optimistic Updates
274
+ ## Optimistic Updates (TanStack Query)
256
275
 
257
276
  ```tsx
258
- // Show result immediately, rollback on error
277
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
278
+
259
279
  function ToggleFavorite({ item }: { item: Item }) {
260
- const [optimistic, setOptimistic] = useState(item.isFavorite);
261
-
262
- const toggle = () => {
263
- setOptimistic(!optimistic); // Instant UI
264
- router.post(`/items/${item.id}/favorite`, {}, {
265
- preserveState: true,
266
- onError: () => {
267
- setOptimistic(item.isFavorite); // Rollback
268
- toast.error('Failed to update');
269
- },
270
- });
271
- };
280
+ const queryClient = useQueryClient();
281
+
282
+ const mutation = useMutation({
283
+ mutationFn: () =>
284
+ fetch(`/api/items/${item.id}/favorite`, { method: 'POST' }).then((res) => {
285
+ if (!res.ok) throw new Error('Failed');
286
+ return res.json();
287
+ }),
288
+ onMutate: async () => {
289
+ await queryClient.cancelQueries({ queryKey: ['items'] });
290
+ const previous = queryClient.getQueryData<Item[]>(['items']);
291
+
292
+ queryClient.setQueryData<Item[]>(['items'], (old) =>
293
+ old?.map((i) =>
294
+ i.id === item.id ? { ...i, isFavorite: !i.isFavorite } : i
295
+ )
296
+ );
297
+
298
+ return { previous };
299
+ },
300
+ onError: (_err, _vars, context) => {
301
+ queryClient.setQueryData(['items'], context?.previous);
302
+ toast.error('Failed to update');
303
+ },
304
+ onSettled: () => {
305
+ queryClient.invalidateQueries({ queryKey: ['items'] });
306
+ },
307
+ });
272
308
 
273
309
  return (
274
- <button onClick={toggle} className="text-xl">
275
- {optimistic ? '❤️' : '🤍'}
310
+ <button onClick={() => mutation.mutate()} className="text-xl">
311
+ {item.isFavorite ? '❤️' : '🤍'}
276
312
  </button>
277
313
  );
278
314
  }
@@ -294,5 +330,5 @@ function ToggleFavorite({ item }: { item: Item }) {
294
330
  1. **`if (loading) return <Spinner />`** — check `loading && !data` instead
295
331
  2. **Silent catch** — always toast/display errors to user
296
332
  3. **No empty state** — every list needs one
297
- 4. **Clickable button during submit** — always `disabled={processing}`
333
+ 4. **Clickable button during submit** — always `disabled={isPending}` or `disabled={isSubmitting}`
298
334
  5. **Console.log-only errors** — user must see feedback
@@ -15,7 +15,7 @@
15
15
  ## Setup (v4)
16
16
 
17
17
  ```css
18
- /* resources/css/app.css (Laravel + Inertia) */
18
+ /* src/app/globals.css */
19
19
  @import "tailwindcss";
20
20
 
21
21
  @theme {
@@ -113,18 +113,38 @@ if (result.success) {
113
113
 
114
114
  ### Environment Variables
115
115
 
116
+ > **Split server and client env schemas.** `NEXT_PUBLIC_*` is embedded in the browser bundle — NEVER put secrets there.
117
+
116
118
  ```tsx
117
- const EnvSchema = z.object({
118
- NEXT_PUBLIC_API_URL: z.string().url(),
119
- NEXT_PUBLIC_STRIPE_KEY: z.string().startsWith('pk_'),
119
+ // lib/env.server.ts Server-only secrets (NEVER import from client components)
120
+ const ServerEnvSchema = z.object({
120
121
  DATABASE_URL: z.string().min(1),
122
+ OPENAI_KEY: z.string().startsWith('sk-'),
123
+ STRIPE_SECRET_KEY: z.string().startsWith('sk_'),
121
124
  NODE_ENV: z.enum(['development', 'production', 'test']),
122
125
  });
123
126
 
124
- // Validate at app startup
125
- export const env = EnvSchema.parse(process.env);
127
+ export const serverEnv = ServerEnvSchema.parse({
128
+ DATABASE_URL: process.env['DATABASE_URL'],
129
+ OPENAI_KEY: process.env['OPENAI_KEY'],
130
+ STRIPE_SECRET_KEY: process.env['STRIPE_SECRET_KEY'],
131
+ NODE_ENV: process.env['NODE_ENV'],
132
+ });
133
+
134
+ // lib/env.client.ts — Public vars only (safe for browser)
135
+ const ClientEnvSchema = z.object({
136
+ NEXT_PUBLIC_APP_URL: z.string().url(),
137
+ NEXT_PUBLIC_STRIPE_KEY: z.string().startsWith('pk_'),
138
+ });
139
+
140
+ export const clientEnv = ClientEnvSchema.parse({
141
+ NEXT_PUBLIC_APP_URL: process.env['NEXT_PUBLIC_APP_URL'],
142
+ NEXT_PUBLIC_STRIPE_KEY: process.env['NEXT_PUBLIC_STRIPE_KEY'],
143
+ });
126
144
  ```
127
145
 
146
+ **Rule:** If a variable contains a key, secret, token, or password, it MUST be in `ServerEnvSchema` without `NEXT_PUBLIC_` prefix.
147
+
128
148
  ### Reusable Schemas
129
149
 
130
150
  ```tsx
@@ -160,26 +180,72 @@ const ContactSchema = z.object({
160
180
  });
161
181
  ```
162
182
 
163
- ## Integration with Laravel (Inertia.js)
183
+ ## Integration with Next.js Server Actions
164
184
 
165
185
  ```tsx
166
- // Frontend validates BEFORE sending to Laravel
167
- const StoreLeadSchema = z.object({
186
+ 'use server';
187
+
188
+ import { z } from 'zod';
189
+
190
+ const CreateLeadSchema = z.object({
168
191
  name: z.string().min(2),
169
- email: EmailSchema,
170
- domain_id: UUIDSchema,
192
+ email: z.string().email().toLowerCase().trim(),
193
+ domainId: z.string().uuid(),
171
194
  });
172
195
 
173
- // In component
174
- const handleSubmit = (formData: unknown) => {
175
- const result = StoreLeadSchema.safeParse(formData);
196
+ export async function createLead(formData: FormData) {
197
+ const result = CreateLeadSchema.safeParse({
198
+ name: formData.get('name'),
199
+ email: formData.get('email'),
200
+ domainId: formData.get('domainId'),
201
+ });
202
+
176
203
  if (!result.success) {
177
- setErrors(result.error.flatten().fieldErrors);
178
- return;
204
+ return { errors: result.error.flatten().fieldErrors };
179
205
  }
180
- // Send validated data to Laravel
181
- router.post('/leads', result.data);
182
- };
206
+
207
+ await db.lead.create({ data: result.data });
208
+ return { success: true };
209
+ }
210
+ ```
211
+
212
+ ### Client-Side with React Hook Form
213
+
214
+ ```tsx
215
+ 'use client';
216
+
217
+ import { useForm } from 'react-hook-form';
218
+ import { zodResolver } from '@hookform/resolvers/zod';
219
+
220
+ const CreateLeadSchema = z.object({
221
+ name: z.string().min(2),
222
+ email: z.string().email(),
223
+ domainId: z.string().uuid(),
224
+ });
225
+
226
+ type CreateLeadForm = z.infer<typeof CreateLeadSchema>;
227
+
228
+ export function LeadForm() {
229
+ const { register, handleSubmit, formState: { errors } } = useForm<CreateLeadForm>({
230
+ resolver: zodResolver(CreateLeadSchema),
231
+ });
232
+
233
+ const onSubmit = async (data: CreateLeadForm) => {
234
+ await fetch('/api/leads', {
235
+ method: 'POST',
236
+ headers: { 'Content-Type': 'application/json' },
237
+ body: JSON.stringify(data),
238
+ });
239
+ };
240
+
241
+ return (
242
+ <form onSubmit={handleSubmit(onSubmit)}>
243
+ <input {...register('name')} />
244
+ {errors.name && <span>{errors.name.message}</span>}
245
+ {/* ... */}
246
+ </form>
247
+ );
248
+ }
183
249
  ```
184
250
 
185
251
  ## FORBIDDEN
@@ -114,6 +114,104 @@ export async function generateMetadata({ params }: { params: { id: string } }) {
114
114
  }
115
115
  ```
116
116
 
117
+ ## Environment Variables & API Security (MANDATORY)
118
+
119
+ > **NEXT_PUBLIC_ vars are embedded in the browser JS bundle.** Anyone can see them in DevTools.
120
+
121
+ ### Server vs Client Environment
122
+
123
+ | Prefix | Accessible from | Safe for |
124
+ |--------|----------------|----------|
125
+ | No prefix | Server Components, Route Handlers, Server Actions | API keys, secrets, tokens, DB URLs |
126
+ | `NEXT_PUBLIC_*` | Server + Browser (embedded in JS) | Public URLs, analytics IDs, publishable keys |
127
+
128
+ ### FORBIDDEN Environment Patterns
129
+
130
+ ```bash
131
+ # NEVER DO THIS — secret exposed in browser bundle
132
+ NEXT_PUBLIC_OPENAI_KEY=sk-abc123
133
+ NEXT_PUBLIC_STRIPE_SECRET_KEY=sk_live_abc
134
+ NEXT_PUBLIC_DATABASE_URL=postgresql://user:pass@host/db
135
+
136
+ # CORRECT — server-only (no NEXT_PUBLIC_ prefix)
137
+ OPENAI_KEY=sk-abc123
138
+ STRIPE_SECRET_KEY=sk_live_abc
139
+ DATABASE_URL=postgresql://user:pass@host/db
140
+
141
+ # OK as NEXT_PUBLIC_ — no secret value
142
+ NEXT_PUBLIC_APP_URL=https://myapp.com
143
+ NEXT_PUBLIC_STRIPE_KEY=pk_live_abc
144
+ NEXT_PUBLIC_GA_ID=G-XXXXX
145
+ ```
146
+
147
+ ### API Proxy Pattern (MANDATORY)
148
+
149
+ External API calls with secrets MUST go through server-side Route Handlers:
150
+
151
+ ```tsx
152
+ // app/api/ai/route.ts — Secret stays on server
153
+ import { NextRequest, NextResponse } from 'next/server';
154
+
155
+ export async function POST(req: NextRequest) {
156
+ const { prompt } = await req.json();
157
+
158
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
159
+ method: 'POST',
160
+ headers: {
161
+ 'Content-Type': 'application/json',
162
+ Authorization: `Bearer ${process.env['OPENAI_KEY']}`,
163
+ },
164
+ body: JSON.stringify({
165
+ model: 'gpt-4',
166
+ messages: [{ role: 'user', content: prompt }],
167
+ }),
168
+ });
169
+
170
+ if (!response.ok) {
171
+ return NextResponse.json({ error: 'AI request failed' }, { status: 502 });
172
+ }
173
+
174
+ return NextResponse.json(await response.json());
175
+ }
176
+ ```
177
+
178
+ ```tsx
179
+ // components/chat.tsx — Client calls YOUR route, not external API
180
+ 'use client';
181
+
182
+ async function sendMessage(prompt: string) {
183
+ const res = await fetch('/api/ai', {
184
+ method: 'POST',
185
+ headers: { 'Content-Type': 'application/json' },
186
+ body: JSON.stringify({ prompt }),
187
+ });
188
+ return res.json();
189
+ }
190
+ ```
191
+
192
+ ### Server Actions for Mutations
193
+
194
+ Server Actions also keep secrets server-side:
195
+
196
+ ```tsx
197
+ // app/actions/payment.ts
198
+ 'use server';
199
+
200
+ import Stripe from 'stripe';
201
+
202
+ const stripe = new Stripe(process.env['STRIPE_SECRET_KEY']!);
203
+
204
+ export async function createCheckout(priceId: string) {
205
+ const session = await stripe.checkout.sessions.create({
206
+ mode: 'payment',
207
+ line_items: [{ price: priceId, quantity: 1 }],
208
+ success_url: `${process.env['APP_URL']}/success`,
209
+ cancel_url: `${process.env['APP_URL']}/cancel`,
210
+ });
211
+ return { url: session.url };
212
+ }
213
+ ```
214
+
117
215
  ## FORBIDDEN
118
216
 
119
217
  1. **`'use client'` on server-capable components** — default to server
@@ -121,3 +219,6 @@ export async function generateMetadata({ params }: { params: { id: string } }) {
121
219
  3. **`getServerSideProps` / `getStaticProps`** — App Router uses async components
122
220
  4. **API routes for server-only data** — use server components directly
123
221
  5. **Prop drilling through layouts** — use parallel routes or context
222
+ 6. **`NEXT_PUBLIC_` with API keys, secrets, or tokens** — secrets leak to browser bundle
223
+ 7. **Calling external APIs from client components** — use Route Handlers as proxy
224
+ 8. **`process.env['SECRET']` in `'use client'` files** — only `NEXT_PUBLIC_*` vars work client-side