Skip to content

Update AI Rules & Docs #431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file added opensaas-sh/blog/src/assets/ai/vibe-boi.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 49 additions & 0 deletions opensaas-sh/blog/src/content/docs/guides/vibe-coding.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: Vibe Coding with Open SaaS
banner:
content: |
Have an Open SaaS app in production? <a href="https://e44cy1h4s0q.typeform.com/to/EPJCwsMi">We'll send you some swag! 👕</a>
---
import { Image } from 'astro:assets';
import llmsFullCursor from '@assets/ai/llm-full-cursor.webp';
import llmsTextChat from '@assets/ai/llm-txt-chat.webp';
import vibeBoi from '@assets/ai/vibe-boi.png';

<Image src={vibeBoi} alt="vibe boi" width={300} />

If you're looking to use AI to help build (or "vibe code") your SaaS app, this guide is for you.

## Coding with AI, Open SaaS, & Wasp

Wasp is particularly well suited to coding with AI due to its central config file which gives LLMs context about the entire full-stack app, and its ability to manage boilerplate code so AI doesn't have to.

Regardless, there are still some shortcomings to using AI to code with Wasp, as well as a learning curve to using it effectively.

Luckily, we did the work for you and put together a bunch of resources to help you use Wasp & Open SaaS with AI as effectively as possible.

### AI Resources in the Template

The template comes with:
- A full set of rules files, `app/.cursor/rules`, to be used with Cursor or adapted to your coding tool of choice (Windsurf, Claude Code, etc.).
- A set of example prompts, `app/.cursor/example-prompts.md`, to help you get started.

### LLM-Friendly Documentation

We've also created a bunch of LLM-friendly documentation:
- [Open SaaS Docs - LLMs.txt](https://docs.opensaas.sh/llms.txt) - Links to the raw text docs.
- [Open SaaS Docs - LLMs-full.txt](https://docs.opensaas.sh/llms-full.txt) - Complete docs as one text file.
- [Wasp Docs - LLMs.txt](https://wasp.sh/llms.txt) - Links to the raw text docs.
- [Wasp Docs - LLMs-full.txt](https://wasp.sh/llms-full.txt) - Complete docs as one text file.
Comment on lines +35 to +36
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose we'll merge this first: wasp-lang/wasp#2772

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah that was my assumption.


Add these to your AI-assisted IDE settings so you can easily reference them in your chat sessions with the LLM.
**In most cases, you'll want to pass the `llms-full.txt` url to the LLM and ask it to help you with a specific task.**

<Image src={llmsFullCursor} alt="add llms-full.txt to settings" />

<Image src={llmsTextChat} alt="add llms.txt to settings" />

### More AI-assisted Coding Learning Resources

Here's a list of articles and tutorials we've made:
- [3hr YouTube tutorial: Vibe Coding a Personal Finance App w/ Wasp & Cursor](https://www.youtube.com/watch?v=WYzEROo7reY)
- [Article: A Structured Workflow for "Vibe Coding" Full-Stack Apps](https://dev.to/wasp/a-structured-workflow-for-vibe-coding-full-stack-apps-352l)
14 changes: 14 additions & 0 deletions template/app/.cursor/example-prompts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
## Example Prompts

### PRD / initial prompt

I want to create a `<insert-type-of-app-here>` app with the current SaaS boilerplate template project I'm in which uses Wasp and already has payment processing, AWS S3 file upload, a landing page, an admin dashboard, and authentication already setup. Leveraging Wasp's full-stack features (such as Auth), let's build the app based on the following spec:
- `<insert-feature-spec-here>`
- `<insert-feature-spec-here>`
- `<insert-feature-spec-here>`

With this in mind, I want you to first evaluate the project template and think about a few possible PRD approaches before landing on the best one. Provide reasoning why this would be the best approach. Remember we're using Wasp, a full-stack framework with batteries included, that can do some of the heavy lifting for us, and we want to use a modified vertical slice implementation approach for LLM-assisted coding so we can start with basic implementations of features first, and add on complexity from there.

### Plan prompt

From this PRD, create an actionable, step-by-step plan that we can use as a guide for LLM-assisted coding. Remember that this project is a SaaS boilerplate template with many features already implemented. Each feature is organized into its own folder (e.g. `src/payment`) with its client and server code split into subfolders and files. Before you create the plan, think about a few different plan styles that would be suitable for this project and the implmentation style before selecting the best one. Give your reasoning for why you think we should use this plan style. Remember that we will constantly refer to this plan to guide our coding implementation so it should be well structured, concise, and actionable, while still providing enough information to guide the LLM.
109 changes: 109 additions & 0 deletions template/app/.cursor/rules/advanced-troubleshooting.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
---
description:
globs:
alwaysApply: true
---
# 6. Advanced Features & Troubleshooting

This document covers advanced Wasp capabilities like Jobs, API Routes, and Middleware, along with performance optimization tips and common troubleshooting steps.

## Advanced Features ( [main.wasp](mdc:main.wasp) )

These features are configured in [main.wasp](mdc:main.wasp).

### Jobs and Workers

- Wasp supports background jobs, useful for tasks like sending emails, processing data, or scheduled operations.
- Jobs require a job executor like PgBoss (which requires PostgreSQL, see [database-operations.mdc](mdc:template/app/.cursor/rules/database-operations.mdc)).
- Example Job definition in [main.wasp](mdc:main.wasp):
```wasp
job emailSender {
executor: PgBoss, // Requires PostgreSQL
// Define the function that performs the job
perform: {
fn: import { sendEmail } from "@src/server/jobs/emailSender.js"
},
// Grant access to necessary entities
entities: [User, EmailQueue]
}
```
- Jobs can be scheduled or triggered programmatically from Wasp actions or other jobs.
- See the Wasp Recurring Jobs Docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc)

### Custom HTTP API Endpoints

- Define custom server API endpoints, often used for external integrations (webhooks, third-party services) where Wasp Operations are not suitable.
- Example API route definition in [main.wasp](mdc:main.wasp):
```wasp
api stripeWebhook {
// Implementation function in server code
fn: import { handleStripeWebhook } from "@src/server/apis/stripe.js",
// Define the HTTP method and path
httpRoute: (POST, "/webhooks/stripe"),
// Optional: Grant entity access
entities: [User, Payment],
// Optional: Apply middleware config function
// middlewareConfigFn: import { apiMiddleware } from "@src/apis"
// Optional: If auth is enabled, this will default to true and provide a context.user
// object. If you do not wish to attempt to parse the JWT in the Authorization Header
// you should set this to false.
// auth: false
}
```
- See the Wasp Custom HTTP API Endpoints docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc)

### Middleware

- Wasp supports custom middleware functions that can run before API route handlers or Page components.
- Useful for logging, custom checks, request transformation, etc.
- Example Middleware definition in [main.wasp](mdc:main.wasp):
```wasp
// Customize global middleware
app todoApp {
// ...
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
```
- See the Wasp Middleware Docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc)

## Performance Optimization

- **Operation Dependencies:** Use specific entity dependencies (`entities: [Task]`) in your Wasp operations ([main.wasp](mdc:main.wasp)) to ensure queries are automatically refetched only when relevant data changes.
- **Pagination:** For queries returning large lists of data, implement pagination logic in your server operation and corresponding UI controls on the client.
- **React Optimization:**
- Use `React.memo` for components that re-render often with the same props.
- Use `useMemo` to memoize expensive calculations within components.
- Use `useCallback` to memoize functions passed down as props to child components (especially event handlers).
- **Optimistic UI Updates (Actions):**
- For actions where perceived speed is critical (e.g., deleting an item, marking as complete), consider using Wasp's `useAction` hook (from `wasp/client/operations`) with `optimisticUpdates`.
- This updates the client-side cache (affecting relevant `useQuery` results) *before* the action completes on the server, providing instant feedback.
- **Use Sparingly:** Only implement optimistic updates where the action is highly likely to succeed and the instant feedback significantly improves UX. Remember to handle potential server-side failures gracefully (Wasp helps revert optimistic updates on error).
- See the Wasp Actions docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc)

## Troubleshooting

- **Wasp Type/Import Errors:** If you encounter TypeScript errors related to missing Wasp imports (e.g., from `wasp/client/operations`, `wasp/entities`, `wasp/server`) or unexpected type mismatches after modifying [main.wasp](mdc:main.wasp) or [schema.prisma](mdc:schema.prisma) , **prompt the user to restart the Wasp development server** (`wasp start`) before further debugging. Wasp needs to regenerate code based on these changes.
- **Operations Not Working:**
- Check that all required `entities` are listed in the operation's definition in [main.wasp](mdc:main.wasp).
- Verify the import path (`fn: import { ... } from "@src/..."`) in [main.wasp](mdc:main.wasp) is correct.
- Check for runtime errors in the Wasp server console where `wasp start` is running.
- Ensure client-side calls match the expected arguments and types.
- **Auth Not Working:**
- Verify the `auth` configuration in [main.wasp](mdc:main.wasp) (correct `userEntity`, `methods`, `onAuthFailedRedirectTo`).
- Ensure `userEntity` in [main.wasp](mdc:main.wasp) matches the actual `User` model name in [schema.prisma](mdc:schema.prisma).
- Check Wasp server logs for auth-related errors.
- If using social auth, confirm environment variables (e.g., `GOOGLE_CLIENT_ID`) are correctly set (e.g., in a `.env.server` file) and loaded by Wasp.
- **Database Issues:**
- Ensure your [schema.prisma](mdc:schema.prisma) syntax is correct.
- Run `wasp db migrate-dev "Migration description"` after schema changes to apply them.
- If using PostgreSQL, ensure the database server is running.
- Check the `.env.server` file for the correct `DATABASE_URL`.
- **Build/Runtime Errors:**
- Check import paths carefully (Wasp vs. relative vs. `@src/` rules, see [project-conventions.mdc](mdc:template/app/.cursor/rules/project-conventions.mdc)).
- Ensure all dependencies are installed (`npm install`).
- Check the Wasp server console and the browser's developer console for specific error messages.

### Referencing Wasp Documentation
- Search for and reference applicable LLM-optimized docs, available in [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc)
167 changes: 167 additions & 0 deletions template/app/.cursor/rules/authentication.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
---
description:
globs:
alwaysApply: true
---
# 4. Authentication

This document gives a quick rundown on how authentication is configured and used within the Wasp application.

See the Wasp Auth docs for available methods and complete guides [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc)

## Wasp Auth Setup

- Wasp provides built-in authentication with minimal configuration via the Wasp config file.
- Wasp generates all necessary auth routes, middleware, and UI components based on the configuration.
- Example auth configuration in [main.wasp](mdc:main.wasp):
```wasp
app myApp {
// ... other config
auth: {
// Links Wasp auth to your User model in @schema.prisma
userEntity: User,
methods: {
// Enable username/password login
usernameAndPassword: {},
// Enable Google OAuth login
// Requires setting GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env vars
google: {},
// Enable email/password login with verification
email: {
// Set up an email sender (Dummy prints to console)
// See https://wasp-lang.com/docs/auth/email-auth#email-sending
fromField: {
name: "Budgeting Vibe",
email: "noreply@budgetingvibe.com"
},
emailVerification: {
clientRoute: EmailVerificationRoute
},
passwordReset: {
clientRoute: PasswordResetRoute
}
}
},
// Route to redirect to if auth fails
onAuthFailedRedirectTo: "/login",
// Optional: Route after successful signup/login
// onAuthSucceededRedirectTo: "/dashboard"
}
emailSender: {
provider: Dummy // Use Dummy for local dev (prints emails to console)
// provider: SMTP // For production, configure SMTP
}
}

// Define the routes needed by email auth methods
route EmailVerificationRoute { path: "/auth/verify-email", to: EmailVerificationPage }
page EmailVerificationPage { component: import { EmailVerification } from "@src/features/auth/EmailVerificationPage.tsx" }

route PasswordResetRoute { path: "/auth/reset-password", to: PasswordResetPage }
page PasswordResetPage { component: import { PasswordReset } from "@src/features/auth/PasswordResetPage.tsx" }
```

- **Dummy Email Provider Note:** When `emailSender: { provider: Dummy }` is configured in [main.wasp](mdc:main.wasp), Wasp does not send actual emails. Instead, the content of verification/password reset emails, including the clickable link, will be printed directly to the server console where `wasp start` is running.

## Wasp Auth Rules

- **User Model ( [schema.prisma](mdc:schema.prisma) ):**
- Wasp Auth methods handle essential identity fields (like `email`, `password hash`, `provider IDs`, `isVerified`) internally. These are stored in separate Prisma models managed by Wasp (`AuthProvider`, `AuthProviderData`).
- Your Prisma `User` model (specified in [main.wasp](mdc:main.wasp) as `auth.userEntity`) typically **only needs the `id` field** for Wasp to link the auth identity.
```prisma
// Minimal User model in @schema.prisma
model User {
id Int @id @default(autoincrement())
// Add other *non-auth* related fields as needed
// e.g., profile info, preferences, relations to other models
// profileImageUrl String?
// timeZone String? @default("UTC")
}
```
- **Avoid adding** `email`, `emailVerified`, `password`, `username`, or provider-specific ID fields directly to *your* `User` model in [schema.prisma](mdc:schema.prisma) unless you have very specific customization needs that require overriding Wasp's default behavior and managing these fields manually.
- If you need frequent access to an identity field like `email` or `username` for *any* user (not just the logged-in one), see the **Recommendation** in the "Wasp Auth User Fields" section below.

- **Auth Pages:**
- When initially creating Auth pages (Login, Signup), use the pre-built components provided by Wasp for simplicity:
- `import { LoginForm, SignupForm } from 'wasp/client/auth';`
- These components work with the configured auth methods in [main.wasp](mdc:main.wasp).
- You can customize their appearance or build completely custom forms if needed.

- **Protected Routes/Pages:**
- Use the `useAuth` hook from `wasp/client/auth` to access the current user's data and check authentication status.
- Redirect or show alternative content if the user is not authenticated.
```typescript
import { useAuth } from 'wasp/client/auth';
import { Redirect } from 'wasp/client/router'; // Or use Link

const MyProtectedPage = () => {
const { data: user, isLoading, error } = useAuth(); // Returns AuthUser | null

if (isLoading) return <div>Loading...</div>;
// If error, it likely means the auth session is invalid/expired
if (error || !user) {
// Redirect to login page defined in main.wasp (auth.onAuthFailedRedirectTo)
// Or return <Redirect to="/login" />;
return <div>Please log in to access this page.</div>;
}

// User is authenticated, render the page content
// Use helpers like getEmail(user) or getUsername(user) if needed
return <div>Welcome back!</div>; // Access user.id if needed
};
```

## Wasp Auth User Fields (`AuthUser`)

- The `user` object returned by `useAuth()` hook on the client, or accessed via `context.user` in server operations/APIs, is an `AuthUser` object (type imported from `wasp/auth`).
- **Auth-specific fields** (email, username, verification status, provider IDs) live under the nested `identities` property based on the auth method used.
- e.g., `user.identities.email?.email`
- e.g., `user.identities.username?.username`
- e.g., `user.identities.google?.providerUserId`
- **Always check for `null` or `undefined`** before accessing these nested properties, as a user might not have used all configured auth methods.
- **Helpers:** Wasp provides helper functions from `wasp/auth` for easier access to common identity fields on the `AuthUser` object:
- `import { getEmail, getUsername } from 'wasp/auth';`
- `const email = getEmail(user); // Returns string | null`
- `const username = getUsername(user); // Returns string | null`
- **Standard User Entities:** Remember that standard `User` entities fetched via `context.entities.User.findMany()` or similar in server code **DO NOT** automatically include these auth identity fields (`email`, `username`, etc.) by default. They only contain the fields defined directly in your [schema.prisma](mdc:schema.prisma) `User` model.
- **Recommendation:**
- If you need *frequent* access to an identity field like `email` or `username` for *any* user (not just the currently logged-in one accessed via `context.user` or `useAuth`) and want to query it easily via `context.entities.User`, consider this approach:
1. **Add the field directly** to your `User` model in [schema.prisma](mdc:schema.prisma).
```prisma
model User {
id Int @id @default(autoincrement())
email String? @unique // Add if needed frequently
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can reference the userSignupFields hook and how they can set the email on signup? You'll know better which level of details is okay :)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah good idea. I added a note about that in the rule even though its present in the open saas codebase because we will probably use these rules for other projects/templates.

// other fields...
}
```
2. **Ensure this field is populated correctly** when the user signs up or updates their profile. You can do this through the `userSignupFields` property in the wasp config file for each auth method.
```wasp
//main.wasp
auth: {
userEntity: User,
methods: {
email: {
//...
userSignupFields: import { getEmailUserFields } from "@src/auth/userSignupFields"
},
}
}
```
```ts
//userSignupFields.ts
import { defineUserSignupFields } from 'wasp/auth/providers/types';

const userDataSchema = z.object({
email: z.string(),
});

export const getEmailUserFields = defineUserSignupFields({
email: (data) => {
const userData = userDataSchema.parse(data);
return userData.email;
}
})
```
3. This makes the field (`email` in this example) a standard, queryable field on your `User` entity, accessible via `context.entities.User`, separate from the `AuthUser`'s identity structure.

- **Common Issue:** If auth isn't working, first verify the `auth` configuration in [main.wasp](mdc:main.wasp) is correct and matches your intent (correct `userEntity`, enabled `methods`, `onAuthFailedRedirectTo`). Ensure environment variables for social providers are set if applicable. Check the Wasp server logs for errors.
Loading