@thorprovider/create-storefront 0.1.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.
Files changed (75) hide show
  1. package/README.md +119 -0
  2. package/bin/install.js +116 -0
  3. package/commands/sf-add-view.md +21 -0
  4. package/commands/sf-init.md +16 -0
  5. package/commands/sf-theme.md +15 -0
  6. package/commands/sf-view.md +20 -0
  7. package/package.json +40 -0
  8. package/recipes/archetype.schema.json +39 -0
  9. package/recipes/archetypes.json +148 -0
  10. package/recipes/recipe.schema.json +59 -0
  11. package/recipes/recipes.json +90 -0
  12. package/recipes/sections.json +46 -0
  13. package/recipes/validate.mjs +190 -0
  14. package/skills/building-storefronts/SKILL.md +178 -0
  15. package/skills/building-storefronts/references/frontend-integration.md +229 -0
  16. package/skills/json-render-core/SKILL.md +291 -0
  17. package/skills/json-render-next/SKILL.md +194 -0
  18. package/skills/json-render-react/SKILL.md +298 -0
  19. package/skills/json-render-remotion/SKILL.md +111 -0
  20. package/skills/json-render-shadcn/SKILL.md +159 -0
  21. package/skills/json-render-solid/SKILL.md +204 -0
  22. package/skills/nextjs-shadcn/SKILL.md +303 -0
  23. package/skills/nextjs-shadcn/references/architecture.md +499 -0
  24. package/skills/nextjs-shadcn/references/project-setup.md +127 -0
  25. package/skills/nextjs-shadcn/references/shadcn-platform.md +258 -0
  26. package/skills/nextjs-shadcn/references/sidebar.md +274 -0
  27. package/skills/nextjs-shadcn/references/styling.md +555 -0
  28. package/skills/sf-scaffold/SKILL.md +118 -0
  29. package/skills/sf-theme-gen/SKILL.md +44 -0
  30. package/skills/sf-view-gen/SKILL.md +94 -0
  31. package/skills/shadcn-component-discovery/SKILL.md +273 -0
  32. package/skills/shadcn-component-discovery/references/registries.md +226 -0
  33. package/skills/shadcn-theming/SKILL.md +104 -0
  34. package/skills/shadcn-theming/references/templates/theme-setup.md +109 -0
  35. package/skills/shadcn-theming/references/theming-guide.md +90 -0
  36. package/skills/storefront-best-practices/SKILL.md +421 -0
  37. package/skills/storefront-best-practices/reference/components/breadcrumbs.md +123 -0
  38. package/skills/storefront-best-practices/reference/components/cart-popup.md +189 -0
  39. package/skills/storefront-best-practices/reference/components/country-selector.md +298 -0
  40. package/skills/storefront-best-practices/reference/components/footer.md +112 -0
  41. package/skills/storefront-best-practices/reference/components/hero.md +241 -0
  42. package/skills/storefront-best-practices/reference/components/megamenu.md +239 -0
  43. package/skills/storefront-best-practices/reference/components/navbar.md +397 -0
  44. package/skills/storefront-best-practices/reference/components/popups.md +221 -0
  45. package/skills/storefront-best-practices/reference/components/product-card.md +125 -0
  46. package/skills/storefront-best-practices/reference/components/product-reviews.md +217 -0
  47. package/skills/storefront-best-practices/reference/components/product-slider.md +174 -0
  48. package/skills/storefront-best-practices/reference/components/search.md +101 -0
  49. package/skills/storefront-best-practices/reference/connecting-to-backend.md +391 -0
  50. package/skills/storefront-best-practices/reference/design.md +388 -0
  51. package/skills/storefront-best-practices/reference/features/promotions.md +307 -0
  52. package/skills/storefront-best-practices/reference/features/wishlist.md +230 -0
  53. package/skills/storefront-best-practices/reference/layouts/account.md +380 -0
  54. package/skills/storefront-best-practices/reference/layouts/cart.md +316 -0
  55. package/skills/storefront-best-practices/reference/layouts/checkout.md +486 -0
  56. package/skills/storefront-best-practices/reference/layouts/home-page.md +264 -0
  57. package/skills/storefront-best-practices/reference/layouts/order-confirmation.md +231 -0
  58. package/skills/storefront-best-practices/reference/layouts/product-details.md +527 -0
  59. package/skills/storefront-best-practices/reference/layouts/product-listing.md +520 -0
  60. package/skills/storefront-best-practices/reference/layouts/static-pages.md +356 -0
  61. package/skills/storefront-best-practices/reference/medusa.md +307 -0
  62. package/skills/storefront-best-practices/reference/mobile-responsiveness.md +183 -0
  63. package/skills/storefront-best-practices/reference/seo.md +195 -0
  64. package/templates/app/app/[[...slug]]/page.tsx +17 -0
  65. package/templates/app/app/[[...slug]]/renderer.tsx +10 -0
  66. package/templates/app/app/globals.css +101 -0
  67. package/templates/app/app/layout.tsx +35 -0
  68. package/templates/app/lib/__STOREFRONT__/catalog.ts +132 -0
  69. package/templates/app/lib/__STOREFRONT__/handlers.ts +33 -0
  70. package/templates/app/lib/__STOREFRONT__/registry.tsx +134 -0
  71. package/templates/app/lib/__STOREFRONT__/runtime.ts +25 -0
  72. package/templates/app/lib/__STOREFRONT__/spec/home.ts +62 -0
  73. package/templates/app/lib/__STOREFRONT__/spec/index.ts +59 -0
  74. package/templates/app/lib/__STOREFRONT__/spec/types.ts +14 -0
  75. package/templates/app/lib/__STOREFRONT__/state.ts +35 -0
@@ -0,0 +1,391 @@
1
+ # Connecting to Backend
2
+
3
+ ## Contents
4
+
5
+ - [Overview](#overview)
6
+ - [Detecting the Backend](#detecting-the-backend-critical)
7
+ - [Framework Detection](#framework-detection)
8
+ - [Environment Configuration](#environment-configuration)
9
+ - [Backend-Specific Integration](#backend-specific-integration)
10
+ - [Authentication Patterns](#authentication-patterns)
11
+ - [Cart State Management](#cart-state-management)
12
+ - [Error Handling for Ecommerce](#error-handling-for-ecommerce)
13
+ - [Performance Patterns](#performance-patterns)
14
+ - [Data Fetching with TanStack Query](#data-fetching-with-tanstack-query-recommended)
15
+ - [Checklist](#checklist)
16
+
17
+ ## Overview
18
+
19
+ Best practices for connecting storefront to ecommerce backend APIs. Framework-agnostic patterns for authentication, cart state management, error handling, and performance optimization.
20
+
21
+ **For Medusa-specific integration**, see `reference/medusa.md` for SDK setup, pricing, regions, and Medusa patterns.
22
+
23
+ ## Detecting the Backend (CRITICAL)
24
+
25
+ **Before implementing any backend integration, identify which ecommerce backend is being used.**
26
+
27
+ ### Detection Strategy
28
+
29
+ **1. Check for monorepo structure:**
30
+ ```bash
31
+ # Look for backend directory
32
+ ls -la ../backend
33
+ ls -la ./backend
34
+ ls -la ../../apps/backend
35
+ ```
36
+
37
+ Common monorepo patterns:
38
+ - `/apps/storefront` + `/apps/backend`
39
+ - `/frontend` + `/backend`
40
+ - `/packages/web` + `/packages/api`
41
+
42
+ **2. Check package.json dependencies:**
43
+ ```json
44
+ {
45
+ "dependencies": {
46
+ "@medusajs/js-sdk": "...", // Medusa
47
+ // check other ecommerce frameworks...
48
+ }
49
+ }
50
+ ```
51
+
52
+ **3. Check environment variables:**
53
+ ```bash
54
+ # Look in .env, .env.local, .env.example
55
+ grep -i "api\|backend\|medusa\|shopify\|commerce" .env*
56
+ ```
57
+
58
+ Common patterns:
59
+ - `NEXT_PUBLIC_MEDUSA_BACKEND_URL` → Medusa
60
+ - Custom `API_URL` or `BACKEND_URL` → Other backend
61
+
62
+ **4. If unsure, ASK THE USER:**
63
+
64
+ ```markdown
65
+ I need to connect to the ecommerce backend. Which backend are you using?
66
+
67
+ Options:
68
+ - Medusa (open-source headless commerce)
69
+ - Custom backend
70
+ - Other
71
+ ```
72
+
73
+ ### Backend Documentation and MCP Servers
74
+
75
+ **ALWAYS refer to the backend's official documentation or MCP server for:**
76
+
77
+ - API endpoints and data structures
78
+ - Authentication requirements
79
+ - SDK usage and installation
80
+ - Environment configuration
81
+ - Rate limits and best practices
82
+
83
+ **For Medusa:**
84
+ - Documentation: https://docs.medusajs.com
85
+ - MCP Server: If available, use Medusa MCP server for real-time API information
86
+ - JS SDK docs: https://docs.medusajs.com/resources/js-sdk
87
+ - See `reference/medusa.md` for detailed integration guide
88
+
89
+ **For other backends:**
90
+ - Check the backend's documentation portal
91
+ - Look for MCP server if available
92
+ - Verify API endpoints and authentication methods
93
+ - Never assume API structure without verification
94
+
95
+ **Important:** Do not guess API endpoints or data formats. Always verify with documentation or ask the user to confirm the backend's API structure.
96
+
97
+ ## Framework Detection
98
+
99
+ Identify the frontend framework to determine appropriate data fetching patterns:
100
+
101
+ **Next.js:**
102
+ - App Router: Server Components (async/await), Client Components (useEffect/TanStack Query)
103
+ - Pages Router: getServerSideProps/getStaticProps (server), useEffect (client)
104
+
105
+ **SvelteKit:**
106
+ - Load functions for server-side data
107
+ - Client-side: fetch in component lifecycle
108
+
109
+ **TanStack Start:**
110
+ - Server functions for server-side data
111
+ - Client-side: fetch with React hooks
112
+
113
+ **General Rule:**
114
+ - **Server-side for initial load**: SEO, performance, security (product pages, listings)
115
+ - **Client-side for interactions**: Cart, filters, search, user-specific data
116
+
117
+ ## Environment Configuration
118
+
119
+ **Store API URLs and keys in environment variables:**
120
+
121
+ ```typescript
122
+ // .env.local
123
+ NEXT_PUBLIC_API_URL=https://api.example.com
124
+ NEXT_PUBLIC_PUBLISHABLE_KEY=pk_...
125
+ ```
126
+
127
+ **Framework-specific prefixes:**
128
+ - Next.js: `NEXT_PUBLIC_` for client-side
129
+ - SvelteKit: `PUBLIC_` for client-side
130
+ - Vite-based (TanStack Start): `VITE_` for client-side
131
+
132
+ **Security:**
133
+ - ❌ NEVER expose secret/admin keys in client-side code
134
+ - ✅ Publishable keys are safe for client (Medusa, Stripe)
135
+ - ✅ Secret keys only in server-side code or environment
136
+
137
+ ## Backend-Specific Integration
138
+
139
+ ### Medusa Backend
140
+
141
+ **For complete Medusa integration guide**, see `reference/medusa.md` which covers:
142
+ - SDK installation and setup
143
+ - Vite configuration (for TanStack Start, etc.)
144
+ - TypeScript types from `@medusajs/types`
145
+ - Price display (never divide by 100)
146
+ - Common operations (products, cart, categories, customers)
147
+ - Custom endpoints
148
+ - Region state management
149
+ - Error handling with SDK
150
+
151
+ ### Other Backends
152
+
153
+ For non-Medusa backends (custom APIs, third-party platforms):
154
+
155
+ **1. Consult backend's API documentation** for:
156
+ - Authentication requirements
157
+ - Available endpoints
158
+ - Request/response formats
159
+ - SDK availability (check if official SDK exists)
160
+
161
+ **2. Use backend's official SDK if available** - provides type safety, error handling, and best practices
162
+
163
+ **3. If no SDK, create API client wrapper:**
164
+ - Centralize API calls in one module
165
+ - Group by resource (products, cart, customers, orders)
166
+ - Handle authentication (include tokens/cookies)
167
+ - Handle errors consistently
168
+ - Use native fetch or axios
169
+
170
+ ## Authentication Patterns
171
+
172
+ ### Customer Authentication
173
+
174
+ **Session-based (cookies):**
175
+ - Backend manages session via cookies
176
+ - No manual token management needed
177
+ - Works across page refreshes
178
+ - Common in traditional ecommerce backends
179
+ - Call backend login endpoint, check auth state, logout methods
180
+
181
+ **Token-based (JWT, OAuth):**
182
+ - Store token in localStorage or secure cookie after login
183
+ - Include token in Authorization header for all authenticated requests
184
+ - Common in headless/API-first backends
185
+ - Format: `Authorization: Bearer {token}`
186
+
187
+ ### Protecting Customer Routes
188
+
189
+ **Check authentication before rendering customer-specific pages** (account, orders, addresses):
190
+
191
+ - **Server-side**: Check auth in server functions (getServerSideProps, load functions, etc.). Redirect to login if not authenticated.
192
+ - **Client-side**: Check auth state on mount. Redirect to login if not authenticated.
193
+
194
+ Use framework-specific auth patterns for redirects.
195
+
196
+ ### Cart Access Pattern
197
+
198
+ **Guest carts:**
199
+ - Store cart ID in localStorage or cookie
200
+ - Check for existing cart ID on app load
201
+ - Create new cart if none exists
202
+ - Allows shopping without account
203
+ - Persists across sessions
204
+
205
+ **Logged-in carts:**
206
+ - Associate cart with customer account
207
+ - Syncs across devices
208
+ - **CRITICAL: Merge guest cart with customer cart on login** - Transfer guest cart items to customer's account cart, then clear guest cart ID from localStorage
209
+
210
+ ## Cart State Management
211
+
212
+ **Critical ecommerce pattern**: Cart must be accessible throughout the app.
213
+
214
+ ### Global Cart State
215
+
216
+ **React Context (for simple cases):**
217
+ - Create CartContext and CartProvider
218
+ - Store cart state and cartId (from localStorage)
219
+ - Load cart on mount if cartId exists
220
+ - Provide methods: addItem, removeItem, updateQuantity, clearCart
221
+ - Update cart state after each operation
222
+
223
+ **State management libraries (Zustand, Redux):**
224
+ - Use for complex state requirements
225
+ - Better for large applications
226
+ - Easier to debug with DevTools
227
+ - Same pattern: Store cart, provide actions, sync with backend
228
+
229
+ **Key requirements:**
230
+ - Cart accessible from any component
231
+ - Real-time cart count updates
232
+ - Optimistic UI updates (update UI immediately, sync with backend)
233
+
234
+ ### Cart Cleanup After Order Placement (CRITICAL)
235
+
236
+ **IMPORTANT: After order is successfully placed, you MUST reset the cart state.**
237
+
238
+ **Common issue:** Cart popup and global cart state still show old items after order completion. This happens when cart state isn't cleared after checkout.
239
+
240
+ **Required cleanup actions:**
241
+
242
+ 1. **Clear cart from global state** - Reset cart state to null/empty in Context/Zustand/Redux
243
+ 2. **Clear localStorage cart ID** - Remove cart ID: `localStorage.removeItem('cart_id')`
244
+ 3. **Invalidate cart queries** - If using TanStack Query: `queryClient.invalidateQueries({ queryKey: ['cart'] })`
245
+ 4. **Update cart count to 0** - Navbar and UI should reflect empty cart
246
+
247
+ **When to clear:**
248
+ - After successful order placement (order confirmed)
249
+ - On navigation to order confirmation page
250
+ - Before redirecting to thank you page
251
+
252
+ **Why this is critical:**
253
+ - Prevents "phantom cart" from appearing in cart popup after order
254
+ - Ensures clean state for next shopping session
255
+ - Improves UX by not showing old cart items
256
+
257
+ ## Error Handling for Ecommerce
258
+
259
+ ### Ecommerce-Specific Errors
260
+
261
+ **Out of stock:**
262
+ - Catch errors when adding to cart
263
+ - Check for "out of stock" or "inventory" in error message
264
+ - Show user-friendly message: "Sorry, this item is now out of stock"
265
+ - Update product availability UI to show out of stock
266
+
267
+ **Price changed during checkout:**
268
+ - Compare cart total with expected total
269
+ - If different, show warning: "Prices have been updated. Please review your cart."
270
+ - Highlight changed prices in cart
271
+
272
+ **Payment failed:**
273
+ - Catch errors during order completion
274
+ - Check for specific payment errors: payment_declined, insufficient_funds, etc.
275
+ - Show specific messages:
276
+ - Payment declined → "Payment declined. Please try a different payment method."
277
+ - Insufficient funds → "Insufficient funds. Please use a different card."
278
+ - Generic → "Payment failed. Please try again or contact support."
279
+
280
+ **Session expired:**
281
+ - Catch 401/Unauthorized errors
282
+ - Clear auth state
283
+ - Redirect to login with message: "Your session has expired. Please log in again."
284
+
285
+ ### User-Friendly Error Messages
286
+
287
+ **Transform technical errors to clear messages:**
288
+ - Network/fetch errors → "Unable to connect. Please check your internet connection."
289
+ - Timeout errors → "Request timed out. Please try again."
290
+ - Inventory errors → "This item is no longer available in the requested quantity."
291
+ - Generic fallback → "Something went wrong. Please try again or contact support."
292
+
293
+ **Pattern**: Check error message or status code, map to user-friendly message, show in UI (toast, banner, inline).
294
+
295
+ ## Performance Patterns
296
+
297
+ ### Data Fetching with TanStack Query (RECOMMENDED)
298
+
299
+ **Use TanStack Query for all backend API calls** - provides automatic caching, request deduplication, loading/error states, and optimistic updates.
300
+
301
+ **Installation:** `npm install @tanstack/react-query`
302
+
303
+ **Setup:**
304
+ - Create QueryClient with default options (staleTime: 5 min, retry: 1)
305
+ - Wrap app with QueryClientProvider
306
+
307
+ **Query pattern (for fetching data):**
308
+ - Use `useQuery` with queryKey and queryFn
309
+ - queryKey: Array with resource and identifier `['products', categoryId]`
310
+ - queryFn: API call function
311
+ - Returns: `data`, `isLoading`, `error`
312
+ - Use for: Products, cart, customer data, categories
313
+
314
+ **Mutation pattern (for modifying data):**
315
+ - Use `useMutation` with mutationFn
316
+ - mutationFn: API operation (add to cart, update, delete)
317
+ - onSuccess: Update cache or invalidate queries
318
+ - Returns: `mutate` function, `isPending` state
319
+ - Use for: Add to cart, remove from cart, update quantities, place order
320
+
321
+ **Benefits:**
322
+ - Automatic caching (no manual cache management)
323
+ - Built-in loading/error states
324
+ - Request deduplication
325
+ - Optimistic updates (update UI before server responds)
326
+ - Cache invalidation strategies
327
+
328
+ **Ecommerce-specific usage:**
329
+ - Products: Long stale time (5-10 min) - products don't change often
330
+ - Cart: Short or no stale time - prices/inventory can change
331
+ - Categories: Long stale time - rarely change
332
+
333
+ ### Caching Strategy
334
+
335
+ **Client-side caching:**
336
+ - TanStack Query handles automatically with `staleTime` and `cacheTime`
337
+ - Configure globally or per-query
338
+ - Product data: 5-10 min stale time
339
+ - Cart data: Fresh on every fetch
340
+ - Categories: Long stale time
341
+
342
+ **Server-side caching (framework-specific):**
343
+ - Next.js: Use `revalidate` export or cache configuration
344
+ - Set revalidation period (e.g., 300 seconds for product pages)
345
+ - Static generation with ISR for product pages
346
+
347
+ ### Request Deduplication
348
+
349
+ TanStack Query and modern frameworks handle this automatically - multiple components requesting same data result in single request.
350
+
351
+ ### Pagination Pattern
352
+
353
+ **Offset-based:** Pass limit and offset parameters to API `limit: 24, offset: page * 24`
354
+
355
+ **Cursor-based (better performance):** Pass limit and cursor (last item ID) `limit: 24, cursor: lastProductId`
356
+
357
+ Check backend documentation for supported pagination type.
358
+
359
+ ## Checklist
360
+
361
+ **Essential backend integration:**
362
+
363
+ - [ ] Backend detected (Medusa, Shopify, custom, etc.)
364
+ - [ ] Environment variables configured (API URL, keys)
365
+ - [ ] Framework-specific data fetching patterns identified
366
+ - [ ] **RECOMMENDED: TanStack Query installed and configured for API calls**
367
+ - [ ] Server-side fetching for product pages (SEO)
368
+ - [ ] Client-side fetching for cart and user interactions (use TanStack Query)
369
+ - [ ] Authentication flow implemented (login/logout)
370
+ - [ ] Cart ID persisted in localStorage or cookies
371
+ - [ ] Global cart state management (context or store)
372
+ - [ ] Cart count synced across app
373
+ - [ ] Optimistic UI updates for cart operations
374
+ - [ ] Error handling for out of stock scenarios
375
+ - [ ] Error handling for payment failures
376
+ - [ ] Session expiration handling (redirect to login)
377
+ - [ ] User-friendly error messages (not technical)
378
+ - [ ] Caching strategy for product data
379
+ - [ ] Stock availability checks before checkout
380
+ - [ ] Price change detection and warnings
381
+
382
+ **For Medusa backends, also check:**
383
+ - [ ] Medusa SDK installed (`@medusajs/js-sdk` + `@medusajs/types`)
384
+ - [ ] SDK initialized with baseUrl and publishableKey
385
+ - [ ] Vite SSR config added (if using TanStack Start/Vite)
386
+ - [ ] Using official types from `@medusajs/types`
387
+ - [ ] Not dividing prices by 100 (display as-is)
388
+ - [ ] Region context implemented for multi-region stores
389
+ - [ ] Region passed to cart and product queries
390
+
391
+ See `reference/medusa.md` for complete Medusa integration guide.