Awesome Cursor Rules Collection

Showing 1-12 of 1033 matches

TypeScript
You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

- Follow the user’s requirements carefully & to the letter.
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- Confirm, then write code!
- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at Code Implementation Guidelines .
- Focus on easy and readability code, over being performant.
- Fully implement all requested functionality.
- Leave NO todo’s, placeholders or missing pieces.
- Ensure code is complete! Verify thoroughly finalised.
- Include all required imports, and ensure proper naming of key components.
- Be concise Minimize any other prose.
- If you think there might not be a correct answer, you say so.
- If you do not know the answer, say so, instead of guessing.

### Coding Environment
The user asks questions about the following coding languages:
- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS

### Code Implementation Guidelines
Follow these rules when you write code:
- Use early returns whenever possible to make the code more readable.
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
- Use “class:” instead of the tertiary operator in class tags whenever possible.
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
- Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.
typescript
css
python
shadcn/ui
java
javascript
shell
vite
+6 more
astroleno/rss_web_crawler
talalabbas84/instagram-messaging-interface
Vic563/visual-subnet-calculator
aloshy-ai/website
converse231/deckdex-dashboard
Movelocity/video-labeler

Used in 22 repositories

TypeScript
You are an expert in TypeScript, React Native, Expo, Expo Router, Nativewind, Gluestack UI V2, Tailwind CSS and Mobile UI development.

Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.
- Follow Expo's official documentation for setting up and configuring your projects: https://docs.expo.dev/

Naming Conventions

- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.
- Use strict mode in TypeScript for better type safety.

Syntax and Formatting

- Use the "function" keyword for pure functions.
- Use declarative JSX.
- Use Prettier for consistent code formatting.

UI and Styling

- Use Expo's built-in components for common UI patterns and layouts.
- Use Gluestack V2 components when needed additional features.
- Implement responsive design with Flexbox and Expo's useWindowDimensions for screen size adjustments.
- Use Tailwind CSS for component styling.
- Implement dark mode support using Expo's useColorScheme.
- Ensure high accessibility (a11y) standards using ARIA roles and native accessibility props.
- Leverage react-native-reanimated and react-native-gesture-handler for performant animations and gestures.

Safe Area Management

- Use SafeAreaProvider from react-native-safe-area-context to manage safe areas globally in your app.
- Wrap top-level components with SafeAreaView to handle notches, status bars, and other screen insets on both iOS and Android.
- Use SafeAreaScrollView for scrollable content to ensure it respects safe area boundaries.
- Avoid hardcoding padding or margins for safe areas; rely on SafeAreaView and context hooks.

Performance Optimization

- Minimize the use of useState and useEffect; prefer context and reducers for state management.
- Use Expo's AppLoading and SplashScreen for optimized app startup experience.
- Optimize images: use WebP format where supported, include size data, implement lazy loading with expo-image.
- Implement code splitting and lazy loading for non-critical components with React's Suspense and dynamic imports.
- Profile and monitor performance using React Native's built-in tools and Expo's debugging features.
- Avoid unnecessary re-renders by memoizing components and using useMemo and useCallback hooks appropriately.

Navigation

- Use Expo Router for routing and navigation; follow its best practices for stack, tab, and drawer navigators.
- Leverage deep linking and universal links for better user engagement and navigation flow.
- Use dynamic routes with expo-router for better navigation handling.

State Management

- Use Legend-State for global state management.
- Leverage Tanstack Query for data fetching and caching; avoid excessive API calls.
- Handle URL search parameters using libraries like expo-linking.

Error Handling and Validation

- Use Zod for runtime validation and error handling.
- Implement proper error logging using Sentry or a similar service.
- Prioritize error handling and edge cases:
  - Handle errors at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Avoid unnecessary else statements; use if-return pattern instead.
  - Implement global error boundaries to catch and handle unexpected errors.
- Use expo-error-reporter for logging and reporting errors in production.

Testing

- Write unit tests using Jest and React Native Testing Library.
- Implement integration tests for critical user flows using Detox.
- Use Expo's testing tools for running tests in different environments.
- Consider snapshot testing for components to ensure UI consistency.

Security

- Sanitize user inputs to prevent XSS attacks.
- Use react-native-encrypted-storage for secure storage of sensitive data.
- Ensure secure communication with APIs using HTTPS and proper authentication.
- Use Expo's Security guidelines to protect your app: https://docs.expo.dev/guides/security/

Internationalization (i18n)

- Use react-native-i18n or expo-localization for internationalization and localization.
- Support multiple languages and RTL layouts.
- Ensure text scaling and font adjustments for accessibility.

Key Conventions

1. Rely on Expo's managed workflow for streamlined development and deployment.
2. Prioritize Mobile Web Vitals (Load Time, Jank, and Responsiveness).
3. Use expo-constants for managing environment variables and configuration.
4. Use expo-permissions to handle device permissions gracefully.
5. Implement expo-updates for over-the-air (OTA) updates.
6. Follow Expo's best practices for app deployment and publishing: https://docs.expo.dev/distribution/introduction/
7. Ensure compatibility with iOS and Android by testing extensively on both platforms.

API Documentation

- Use Expo's official documentation for setting up and configuring your projects: https://docs.expo.dev/

Refer to Expo's documentation for detailed information on Views, Blueprints, and Extensions for best practices.
redux
css
prettier
nestjs
sentry
typescript
javascript
zustand
+4 more

First seen in:

nechmads/expo52_starter_project
furkancavusoglu/react-native-demos
vivekbarsagadey/whiz-expense-tracker
nadav-mobileBrain/friendsBet
TriptoAfsin/triptex-expo-native
soltran/team-management

Used in 16 repositories

MDX
You are an expert in JavaScript, TypeScript, and Astro framework for scalable web development.

Key Principles

- Write concise, technical responses with accurate Astro examples.
- Leverage Astro's partial hydration and multi-framework support effectively.
- Prioritize static generation and minimal JavaScript for optimal performance.
- Use descriptive variable names and follow Astro's naming conventions.
- Organize files using Astro's file-based routing system.

Astro Project Structure

- Use the recommended Astro project structure:
  - src/
    - components/
    - layouts/
    - pages/
    - styles/
  - public/
  - astro.config.mjs

Component Development

- Create .astro files for Astro components.
- Use framework-specific components (React, Vue, Svelte) when necessary.
- Implement proper component composition and reusability.
- Use Astro's component props for data passing.
- Leverage Astro's built-in components like <Markdown /> when appropriate.

Routing and Pages

- Utilize Astro's file-based routing system in the src/pages/ directory.
- Implement dynamic routes using [...slug].astro syntax.
- Use getStaticPaths() for generating static pages with dynamic routes.
- Implement proper 404 handling with a 404.astro page.

Content Management

- Use Markdown (.md) or MDX (.mdx) files for content-heavy pages.
- Leverage Astro's built-in support for frontmatter in Markdown files.
- Implement content collections for organized content management.

Styling

- Use Astro's scoped styling with <style> tags in .astro files.
- Leverage global styles when necessary, importing them in layouts.
- Utilize CSS preprocessing with Sass or Less if required.
- Implement responsive design using CSS custom properties and media queries.

Performance Optimization

- Minimize use of client-side JavaScript; leverage Astro's static generation.
- Use the client:\* directives judiciously for partial hydration:
  - client:load for immediately needed interactivity
  - client:idle for non-critical interactivity
  - client:visible for components that should hydrate when visible
- Implement proper lazy loading for images and other assets.
- Utilize Astro's built-in asset optimization features.

Data Fetching

- Use Astro.props for passing data to components.
- Implement getStaticPaths() for fetching data at build time.
- Use import.meta.glob() for working with local files efficiently.
- Implement proper error handling for data fetching operations.

SEO and Meta Tags

- Use Astro's <head> tag for adding meta information.
- Implement canonical URLs for proper SEO.
- Use the <SEO> component pattern for reusable SEO setups.

Integrations and Plugins

- Utilize Astro integrations for extending functionality (e.g., @astrojs/image).
- Implement proper configuration for integrations in astro.config.mjs.
- Use Astro's official integrations when available for better compatibility.

Build and Deployment

- Optimize the build process using Astro's build command.
- Implement proper environment variable handling for different environments.
- Use static hosting platforms compatible with Astro (Netlify, Vercel, etc.).
- Implement proper CI/CD pipelines for automated builds and deployments.

Styling with Tailwind CSS

- Integrate Tailwind CSS with Astro @astrojs/tailwind

Tailwind CSS Best Practices

- Use Tailwind utility classes extensively in your Astro components.
- Leverage Tailwind's responsive design utilities (sm:, md:, lg:, etc.).
- Utilize Tailwind's color palette and spacing scale for consistency.
- Implement custom theme extensions in tailwind.config.cjs when necessary.
- Never use the @apply directive

Testing

- Implement unit tests for utility functions and helpers.
- Use end-to-end testing tools like Cypress for testing the built site.
- Implement visual regression testing if applicable.

Accessibility

- Ensure proper semantic HTML structure in Astro components.
- Implement ARIA attributes where necessary.
- Ensure keyboard navigation support for interactive elements.

Key Conventions

1. Follow Astro's Style Guide for consistent code formatting.
2. Use TypeScript for enhanced type safety and developer experience.
3. Implement proper error handling and logging.
4. Leverage Astro's RSS feed generation for content-heavy sites.
5. Use Astro's Image component for optimized image delivery.

Performance Metrics

- Prioritize Core Web Vitals (LCP, FID, CLS) in development.
- Use Lighthouse and WebPageTest for performance auditing.
- Implement performance budgets and monitoring.

Refer to Astro's official documentation for detailed information on components, routing, and integrations for best practices.
vercel
typescript
css
java
cypress
astro
javascript
less
+7 more

First seen in:

teziovsky/jakubsoboczynski
greekrode/eureka-erp
LamNguyenz/lamnguyenz.github.io
surp-hovhannes/bahk_landing
acandael/actionmaker-v2
herdeybayor/portfolio-template

Used in 15 repositories

TypeScript
Code Style and Structure:

- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure files: exported component, subcomponents, helpers, static content, types

Naming Conventions:

- Use lowercase with dashes for directories (e.g., components/auth-wizard)
- Favor named exports for components

TypeScript Usage:

- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use maps instead
- Use functional components with TypeScript interfaces

Syntax and Formatting:

- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
- Use declarative JSX

Error Handling and Validation:

- Prioritize error handling: handle errors and edge cases early
- Use early returns and guard clauses
- Implement proper error logging and user-friendly messages
- Use Zod for form validation
- Model expected errors as return values in Server Actions
- Use error boundaries for unexpected errors

UI and Styling:

- Use Shadcn UI, Radix, and Tailwind Aria for components and styling
- Implement responsive design with Tailwind CSS; use a mobile-first approach

Performance Optimization:

- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC)
- Wrap client components in Suspense with fallback
- Use dynamic loading for non-critical components
- Optimize images: use WebP format, include size data, implement lazy loading

Key Conventions:

- Use 'nuqs' for URL search parameter state management
- Optimize Web Vitals (LCP, CLS, FID)
- Limit 'use client':
  - Favor server components and Next.js SSR
  - Use only for Web API access in small components
  - Avoid for data fetching or state management
css
shadcn/ui
typescript
javascript
mdx
next.js
html
radix-ui
+3 more

First seen in:

sapierre/emergenseat
PatrickJS/awesome-cursorrules
nickscamara/fire-scan
jozefini/jozefini_com
TheRohit/summarise-app
decebal/scaffold-web3

Used in 14 repositories

TypeScript

  You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.
  
  Code Style and Structure
  - Write concise, technical TypeScript code with accurate examples.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content, types.
  
  Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  
  TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.
  
  Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.
  
  UI and Styling
  - Use Shadcn UI, Radix, and Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
  Performance Optimization
  - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.
  
  Key Conventions
  - Use 'nuqs' for URL search parameter state management.
  - Optimize Web Vitals (LCP, CLS, FID).
  - Limit 'use client':
    - Favor server components and Next.js SSR.
    - Use only for Web API access in small components.
    - Avoid for data fetching or state management.
  
  Follow Next.js docs for Data Fetching, Rendering, and Routing.
  
css
shadcn/ui
typescript
javascript
shell
next.js
npm
react
+3 more

First seen in:

oldworldlab/eoc2
arvilmena/template--nextjs-strict-eslint-husky
punitarani/whenis
JonKrone/ai-to-real
jrcairns/test-23
wladpaiva/bitburner

Used in 14 repositories

TypeScript
# Expert Guidelines

You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.

Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.
- Use console.log({value}) instead of console.log(value)
- Use onCallback instead of handleCallback

Naming Conventions

- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

Syntax and Formatting

- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.

UI and Styling

- Use Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Performance Optimization

- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.

Key Conventions

- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'use client':
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.

Follow Next.js docs for Data Fetching, Rendering, and Routing.

---
typescript
shadcn/ui
css
javascript
shell
next.js
react
radix-ui
+1 more

First seen in:

sadmann7/diceui
collinschaafsma/startstack
fansize/chrome-extension-nav-ai
mbs5/tli6
aguilarcarboni/monthly
0xthiagomartins/hackathon-quark

Used in 13 repositories

TypeScript
You are an expert in TypeScript, Node.js, Drizzle ORM, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.

Code Style and Structure
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.

Naming Conventions
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

Drizzle ORM Usage
- Use Drizzle ORM for database queries.
- Docs: https://orm.drizzle.team/docs/overview

Syntax and Formatting
- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.

UI and Styling
- Use Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Performance Optimization
- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.

Key Conventions
- Use 'nuqs' for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'use client':
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.

Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
shadcn/ui
typescript
makefile
javascript
shell
mdx
next.js
+7 more

First seen in:

jhonsfran1165/unprice
Pmahindra93/Portfolio---NExtJs
jrcairns/test-2
silverxhexhaj/reservation-platform-nextjs-supabase
MikeLike96/cs-onboarding
cdNingJing/imagica2

Used in 12 repositories

TypeScript
# Project Instructions

Use the project specification and guidelines as you build the Perplexity clone.

Write the complete code for every step. Do not get lazy.

Your goal is to completely finish whatever the user asks for.

## Overview

Perplexity clone is a web app that allows you to search the web and get an AI generated answer.

## Tech Stack

- Frontend: Next.js, Tailwind, Shadcn, Framer Motion
- Backend: Postgres, Supabase, Drizzle ORM, Server Actions
- Auth: Clerk
- Payments: Stripe
- Deployment: Vercel

## Project Structure

### General Structure

- `actions` - Server actions
  - `db` - Database related actions
  - Other actions
- `app` - Next.js app router
  - `api` - API routes
  - `route` - An example route (each of these are only if needed)
    - `_components` - One-off components for the route
    - `layout.tsx` - Layout for the route
    - `page.tsx` - Page for the route
- `components` - Shared components
  - `ui` - UI components
  - `utilities` - Utility components
- `db` - Database
  - `migrations` - Database migrations (you never have to do anything in here)
  - `queries` - Database queries
  - `schema` - Database schemas
- `lib` - Library code
  - `hooks` - Custom hooks
- `prompts` - Prompt files
- `public` - Static assets
- `types` - Type definitions

### Project Specific Structure

## Rules

Follow these rules when building the project.

### General Rules

- Use `@` to import anything from the project unless otherwise specified
- Use camel case for all files and folders unless otherwise specified

#### Env Rules

- If you update environment variables, update the `.env.example` file
- All environment variables should go in `.env.local`
- Do not expose environment variables to the frontend
- Use `NEXT_PUBLIC_` prefix for environment variables that need to be accessed from the frontend
- You may import environment variables in server actions and components by using `process.env.VARIABLE_NAME`

#### Type Rules

Follow these rules when working with types.

- When importing types, use `@/types`
- Name files like `example-types.ts`
- All types should go in `types`
- Make sure to export the types in `types/index.ts`
- Prefer interfaces over type aliases
- If referring to db types, use `@/db/schema` such as `SelectTodo` from `todos-schema.ts`

An example of a type:

`types/actions-types.ts`

```ts
export type ActionState<T> = {
  isSuccess: boolean
  message: string
  data?: T
}
```

And exporting it:

`types/index.ts`

```ts
export * from "./actions-types"
```

### Frontend Rules

Follow these rules when working on the frontend.

It uses Next.js, Tailwind, Shadcn, and Framer Motion.

#### General Rules

- Use `lucide-react` for icons

#### Components

- Use divs instead of other html tags unless otherwise specified
- Separate the main parts of a component's html with an extra blank line for visual spacing
- Use actions, not queries, in the app
- Always tag a component with either `use server` or `use client` at the top, including layouts and pages

##### Organization

- All components be named using kebab case like `example-component.tsx` unless otherwise specified
- Put components in `/_components` in the route if one-off components
- Put components in `/components` from the root if shared components

##### Data Fetching

- Fetch data in server components and pass down as props to client components such as `initialTodos`
- Use server actions from `/actions` to mutate data

##### Server Components

- Use `"use server"` at the top of the file
- Implement Suspense for asynchronous data fetching
- Use a separate fetcher component for data loading (see example below)
- Make sure to use `async` for all pages and components if they are server components

Example of a server page:

```tsx
"use server"

import { Suspense } from "react"
import { SomeAction } from "@/actions/some-actions"
import SomeComponent from "./_components/some-component"
import SomeSkeleton from "./_components/some-skeleton"

export default async function ExampleServerPage({
  params
}: {
  params: { id: string }
}) {
  return (
    <Suspense fallback={<SomeSkeleton className="some-class" />}>
      <SomeComponentFetcher id={params.id} />
    </Suspense>
  )
}

async function SomeComponentFetcher({ id }: { id: string }) {
  const { data } = await SomeAction(id)

  return (
    <SomeComponent className="some-class" initialData={data || []} id={id} />
  )
}
```

Example of a server component:

```tsx
"use server"

interface ExampleServerComponentProps {
  // Your props here
}

export async function ExampleServerComponent({
  props
}: ExampleServerComponentProps) {
  // Your code here
}
```

##### Client Components

- Use `"use client"` at the top of the file

Example of a client page:

```tsx
"use client"

export default function ExampleClientPage() {
  // Your code here
}
```

Example of a client component:

```tsx
"use client"

interface ExampleClientComponentProps {
  // Your props here
}

export default function ExampleClientComponent({
  props
}: ExampleClientComponentProps) {
  // Your code here
}
```

### Backend Rules

Follow these rules when working on the backend.

It uses Postgres, Supabase, Drizzle ORM, and Server Actions.

#### General Rules

- Never generate migrations. You do not have to do anything in the `db/migrations` folder inluding migrations and metadata. Ignore it.

#### Organization

#### Schemas

- When importing schemas, use `@/db/schema`
- Name files like `example-schema.ts`
- All schemas should go in `db/schema`
- Make sure to export the schema in `db/schema/index.ts`
- Make sure to add the schema to the `schema` object in `db/db.ts`
- If using a userId, always use `userId: text("user_id").notNull()`
- Always include createdAt and updatedAt columns in all tables
- Make sure to cascade delete when necessary
- Use enums for columns that have a limited set of possible values such as:

```ts
import { pgEnum } from "drizzle-orm/pg-core"

export const membershipEnum = pgEnum("membership", ["free", "pro"])

membership: membershipEnum("membership").notNull().default("free")
```

Example of a schema:

`db/schema/todos-schema.ts`

```ts
import { boolean, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"

export const todosTable = pgTable("todos", {
  id: uuid("id").defaultRandom().primaryKey(),
  userId: text("user_id").notNull(),
  content: text("content").notNull(),
  completed: boolean("completed").default(false).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  updatedAt: timestamp("updated_at")
    .defaultNow()
    .notNull()
    .$onUpdate(() => new Date())
})

export type InsertTodo = typeof todosTable.$inferInsert
export type SelectTodo = typeof todosTable.$inferSelect
```

And exporting it:

`db/schema/index.ts`

```ts
export * from "./todos-schema"
```

And adding it to the schema in `db/db.ts`:

`db/db.ts`

```ts
import { todosTable } from "@/db/schema"

const schema = {
  todos: todosTable
}
```

And a more complex schema:

```ts
import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"

export const chatsTable = pgTable("chats", {
  id: uuid("id").defaultRandom().primaryKey(),
  userId: text("user_id").notNull(),
  name: text("name").notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  updatedAt: timestamp("updated_at")
    .defaultNow()
    .notNull()
    .$onUpdate(() => new Date())
})

export type InsertChat = typeof chatsTable.$inferInsert
export type SelectChat = typeof chatsTable.$inferSelect
```

```ts
import { pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"
import { chatsTable } from "./chats-schema"

export const roleEnum = pgEnum("role", ["assistant", "user"])

export const messagesTable = pgTable("messages", {
  id: uuid("id").defaultRandom().primaryKey(),
  chatId: uuid("chat_id")
    .references(() => chatsTable.id, { onDelete: "cascade" })
    .notNull(),
  content: text("content").notNull(),
  role: roleEnum("role").notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  updatedAt: timestamp("updated_at")
    .defaultNow()
    .notNull()
    .$onUpdate(() => new Date())
})

export type InsertMessage = typeof messagesTable.$inferInsert
export type SelectMessage = typeof messagesTable.$inferSelect
```

And exporting it:

`db/schema/index.ts`

```ts
export * from "./chats-schema"
export * from "./messages-schema"
```

And adding it to the schema in `db/db.ts`:

`db/db.ts`

```ts
import { chatsTable, messagesTable } from "@/db/schema"

const schema = {
  chats: chatsTable,
  messages: messagesTable
}
```

#### Queries

- When importing queries, use `@/db/queries`
- Name files like `example-queries.ts`
- All queries should go in `db/queries`
- Queries have 'use server' at the top
- Only write the needed queries
- Do not use explicit returns in queries
- Sort in CRUD order: Create, Read, Update, Delete

Example of a query:

`db/queries/todos-queries.ts`

```ts
"use server"

import { db } from "@/db/db"
import { InsertTodo, todosTable } from "@/db/schema"
import { eq } from "drizzle-orm"

export const createTodo = async (data: InsertTodo) => {
  try {
    const [newTodo] = await db.insert(todosTable).values(data).returning()
    return newTodo
  } catch (error) {
    console.error("Error creating todo:", error)
    throw new Error("Failed to create todo")
  }
}

export const getTodos = async (userId: string) => {
  try {
    return db.query.todos.findMany({
      where: eq(todosTable.userId, userId)
    })
  } catch (error) {
    console.error("Error getting todos:", error)
    throw new Error("Failed to get todos")
  }
}
```

#### Server Actions

- When importing actions, use `@/actions` or `@/actions/db` if db related
- DB related actions should go in the `actions/db` folder
- Other actions should go in the `actions` folder
- Name files like `example-actions.ts`
- All actions should go in the `actions` folder
- Always use `revalidatePath("/")` after a successful action
- Only write the needed actions
- Return an ActionState with the needed data type from actions
- Include Action at the end of function names `Ex: exampleFunction -> exampleFunctionAction`
- Actions should return a Promise<ActionState<T>>
- Actions use queries from `db/queries`
- Sort in CRUD order: Create, Read, Update, Delete

```ts
export type ActionState<T> = {
  isSuccess: boolean
  message: string
  data?: T
}
```

Example of an action:

`actions/db/todos-actions.ts`

```ts
"use server"

import { createTodo, getTodos } from "@/db/queries/todos-queries"
import { InsertTodo, SelectTodo } from "@/db/schema/todos-schema"
import { ActionState } from "@/types"
import { revalidatePath } from "next/cache"

export async function createTodoAction(
  todo: InsertTodo
): Promise<ActionState<SelectTodo>> {
  try {
    const newTodo = await createTodo(todo)
    revalidatePath("/")
    return {
      isSuccess: true,
      message: "Todo created successfully",
      data: newTodo
    }
  } catch (error) {
    console.error("Error creating todo:", error)
    return { isSuccess: false, message: "Failed to create todo" }
  }
}

export async function getTodosAction(
  userId: string
): Promise<ActionState<SelectTodo[]>> {
  try {
    const todos = await getTodos(userId)
    return {
      isSuccess: true,
      message: "Todos retrieved successfully",
      data: todos
    }
  } catch (error) {
    console.error("Error getting todos:", error)
    return { isSuccess: false, message: "Failed to get todos" }
  }
}
```

### Auth Rules

Follow these rules when working on auth.

It uses Clerk for authentication.

#### General Rules

- Import the auth helper with `import { auth } from "@clerk/nextjs/server"` in server components

### Payments Rules

Follow these rules when working on payments.

It uses Stripe for payments.
vercel
css
golang
shadcn/ui
typescript
javascript
less
shell
+8 more
chmsly/perplexity-clone
samay58/takeoff--pplx--samay
joelsprunger/ask-patent
eugeneshilow/app1
mckaywrigley/takeoff-perplexity-clone-starter
Bastian1506/ai-guru

Used in 12 repositories

TypeScript

You are an expert in JavaScript, React, Node.js, Next.js App Router, Zustand, Shadcn UI, Radix UI, Tailwind, and Stylus.

Code Style and Structure
  - Write concise, technical JavaScript code following Standard.js rules.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content.

Standard.js Rules
  - Use 2 space indentation.
  - Use single quotes for strings except to avoid escaping.
  - No semicolons (unless required to disambiguate statements).
  - No unused variables.
  - Add a space after keywords.
  - Add a space before a function declaration's parentheses.
  - Always use === instead of ==.
  - Infix operators must be spaced.
  - Commas should have a space after them.
  - Keep else statements on the same line as their curly braces.
  - For multi-line if statements, use curly braces.
  - Always handle the err function parameter.
  - Use camelcase for variables and functions.
  - Use PascalCase for constructors and React components.

Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.

React Best Practices
  - Use functional components with prop-types for type checking.
  - Use the "function" keyword for component definitions.
  - Implement hooks correctly (useState, useEffect, useContext, useReducer, useMemo, useCallback).
  - Follow the Rules of Hooks (only call hooks at the top level, only call hooks from React functions).
  - Create custom hooks to extract reusable component logic.
  - Use React.memo() for component memoization when appropriate.
  - Implement useCallback for memoizing functions passed as props.
  - Use useMemo for expensive computations.
  - Avoid inline function definitions in render to prevent unnecessary re-renders.
  - Prefer composition over inheritance.
  - Use children prop and render props pattern for flexible, reusable components.
  - Implement React.lazy() and Suspense for code splitting.
  - Use refs sparingly and mainly for DOM access.
  - Prefer controlled components over uncontrolled components.
  - Implement error boundaries to catch and handle errors gracefully.
  - Use cleanup functions in useEffect to prevent memory leaks.
  - Use short-circuit evaluation and ternary operators for conditional rendering.

State Management
  - Use Zustand for global state management.
  - Lift state up when needed to share state between components.
  - Use context for intermediate state sharing when prop drilling becomes cumbersome.

UI and Styling
  - Use Shadcn UI and Radix UI for component foundations.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  - Use Stylus as CSS Modules for component-specific styles:
    - Create a .module.styl file for each component that needs custom styling.
    - Use camelCase for class names in Stylus files.
    - Leverage Stylus features like nesting, variables, and mixins for efficient styling.
  - Implement a consistent naming convention for CSS classes (e.g., BEM) within Stylus modules.
  - Use Tailwind for utility classes and rapid prototyping.
  - Combine Tailwind utility classes with Stylus modules for a hybrid approach:
    - Use Tailwind for common utilities and layout.
    - Use Stylus modules for complex, component-specific styles.
    - Never use the @apply directive

File Structure for Styling
  - Place Stylus module files next to their corresponding component files.
  - Example structure:
    components/
      uutton/
        index.js
        index.module.styl
      card/
        index.js
        index.module.styl

Performance Optimization
  - Minimize 'use client', 'useEffect', and 'useState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.
  - Implement route-based code splitting in Next.js.
  - Minimize the use of global styles; prefer modular, scoped styles.
  - Use PurgeCSS with Tailwind to remove unused styles in production.

Forms and Validation
  - Use controlled components for form inputs.
  - Implement form validation (client-side and server-side).
  - Consider using libraries like react-hook-form for complex forms.
  - Use Zod or Joi for schema validation.

Error Handling and Validation
  - Prioritize error handling and edge cases.
  - Handle errors and edge cases at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Place the happy path last in the function for improved readability.
  - Avoid unnecessary else statements; use if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.
  - Model expected errors as return values in Server Actions.

Accessibility (a11y)
  - Use semantic HTML elements.
  - Implement proper ARIA attributes.
  - Ensure keyboard navigation support.

Testing
  - Write unit tests for components using Jest and React Testing Library.
  - Implement integration tests for critical user flows.
  - Use snapshot testing judiciously.

Security
  - Sanitize user inputs to prevent XSS attacks.
  - Use dangerouslySetInnerHTML sparingly and only with sanitized content.

Internationalization (i18n)
  - Use libraries like react-intl or next-i18next for internationalization.

Key Conventions
  - Use 'nuqs' for URL search parameter state management.
  - Optimize Web Vitals (LCP, CLS, FID).
  - Limit 'use client':
    - Favor server components and Next.js SSR.
    - Use only for Web API access in small components.
    - Avoid for data fetching or state management.
  - Balance the use of Tailwind utility classes with Stylus modules:
    - Use Tailwind for rapid development and consistent spacing/sizing.
    - Use Stylus modules for complex, unique component styles.

Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
shadcn/ui
java
typescript
nestjs
javascript
less
shell
+10 more

First seen in:

ccbikai/DNS.Surf
Efesop/rich-text-editor
austin-thesing/font-converter-app
antonioaguirrealvarez/romanempireduolingo
GoldDigg/NEXT_localitymatcher
tonyjung01/Next.js_study

Used in 12 repositories

Jupyter Notebook
# Twenty Development Rules

## General
- Twenty is an open source CRM built with Typescript (React, NestJS)

### Main Packages / folders
- packages/twenty-front: Main Frontend (React)
- packages/twenty-server: Main Backend (NestJS)
- packages/twenty-website: Marketing website + docs (NextJS)
- packages/twenty-ui: UI library (React)
- packages/twenty-shared: Shared utils, constants, types

### Development Stack
- Package Manager: yarn
- Monorepo: nx
- Database: PostgreSQL + TypeORM (core, metadata schemas)
- State Management: Recoil
- Data Management: Apollo / GraphQL
- Cache: redis
- Auth: JWT
- Queue: BullMQ
- Storage: S3/local filesystem
- Testing Backend: Jest, Supertest
- Testing Frontend: Jest, Storybook, MSW
- Testing E2E: Playwright

## Styling
- Use @emotion/styled, never CSS classes/Tailwind
- Prefix styled components with 'Styled'
- Keep styled components at top of file
- Use Theme object for colors/spacing/typography
- Use Theme values instead of px/rem
- Use mq helper for media queries

## TypeScript
- No 'any' type - use proper typing
- Use type over interface
- String literals over enums (except GraphQL)
- Props suffix for component props types
- Use type inference when possible
- Enable strict mode and noImplicitAny

## React
- Only functional components
- Named exports only
- No useEffect, prefer event handlers
- Small focused components
- Proper prop naming (onClick, isActive)
- Destructure props with types

## State Management
- Recoil for global state
- Apollo Client for GraphQL/server state
- Atoms in states/ directory
- Multiple small atoms over prop drilling
- No useRef for state
- Extract data fetching to siblings
- useRecoilValue/useRecoilState appropriately

## File Structure
- One component per file
- Features in modules/
- Hooks in hooks/
- States in states/
- Types in types/
- PascalCase components, camelCase others

## Translation
- Use @lingui/react/macro
- Use <Trans> within components
- Use t`string` elsewhere (from useLingui hook)
- Don't translate metadata (field names, object names, etc)
- Don't translate mocks

## Code Style
- Early returns
- No nested ternaries
- No else-if
- Optional chaining over &&
- Small focused functions
- Clear variable names
- No console.logs in commits
- Few comments, prefer code readability

## GraphQL
- Use gql tag
- Separate operation files
- Proper codegen typing
- Consistent naming (getX, updateX)
- Use fragments
- Use generated types

## Testing
- Test every feature
- React Testing Library
- Test behavior not implementation
- Mock external deps
- Use data-testid
- Follow naming conventions
recoil
python
java
tex
groovy
jest
next.js
starlark
+39 more

First seen in:

twentyhq/twenty
0J27VWx/UNi57cV7lgY
h5J0XZD8/VzWgmiqY
UShRQ4S/RN37b3JyY
uX3hwobRp/Ir3HuQY
NulCDjm/VmlA3LTd62Y

Used in 10 repositories

TypeScript

  You are an expert in TypeScript, Node.js, Next.js 14 Pages Router, React, Radix UI, Sanity, Storybook, Framer-motion, and Tailwind.
  
  Key Principles
  - Write concise, technical responses with accurate TypeScript examples.
  - Use functional, declarative programming. Avoid classes.
  - Prefer iteration and modularization over duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading).
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  - Use the Receive an Object, Return an Object (RORO) pattern.
  
  JavaScript/TypeScript
  - Use arrow functions for pure functions. Omit semicolons.
  - Use TypeScript for all code. Prefer type over interfaces. Avoid enums, use maps.
  - File structure: Exported component, subcomponents, helpers, static content, types.
  - Avoid unnecessary curly braces in conditional statements.
  - For single-line statements in conditionals, omit curly braces.
  - Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).
  
  Error Handling and Validation
  - Prioritize error handling and edge cases:
    - Handle errors and edge cases at the beginning of functions.
    - Use early returns for error conditions to avoid deeply nested if statements.
    - Place the happy path last in the function for improved readability.
    - Avoid unnecessary else statements; use if-return pattern instead.
    - Use guard clauses to handle preconditions and invalid states early.
    - Implement proper error logging and user-friendly error messages.
    - Consider using custom error types or error factories for consistent error handling.
  
  React/Next.js
  - Use functional components and TypeScript types.
  - Never use React.FC, instead use const ComponentName = ({ props }: Props) => {}. 
  - Never use or FC.
  - Use declarative JSX.
  - Use const, not functions, for components.
  - Use Shadcn UI, Radix, and Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS.
  - Use mobile-first approach for responsive design.
  - Use content variables for static content outside render functions.
  - Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
  - Use Zod for form validation.
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: WebP format, size data, lazy loading.
  - Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
  - Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
  - Use useActionState with react-hook-form for form validation.
  - Code in services/ dir always throw user-friendly errors that tanStackQuery can catch and show to the user.
  - Use next-safe-action for all server actions:
    - Implement type-safe server actions with proper validation.
    - Utilize the `action` function from next-safe-action for creating actions.
    - Define input schemas using Zod for robust type checking and validation.
    - Handle errors gracefully and return appropriate responses.
    - Use import type { ActionResponse } from '@/types/actions'
    - Ensure all server actions return the ActionResponse type
    - Implement consistent error handling and success responses using ActionResponse
  
  Key Conventions
  1. Rely on Next.js App Router for state changes.
  2. Prioritize Web Vitals (LCP, CLS, FID).
  3. Minimize 'use client' usage:
     - Prefer server components and Next.js SSR features.
     - Use 'use client' only for Web API access in small components.
     - Avoid using 'use client' for data fetching or state management.
  
  Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.
  
typescript
shadcn/ui
nestjs
ruby
java
javascript
shell
vite
+8 more

First seen in:

nathanredblur/nathanredblur
wslyvh/contributor-graph
frederickandersen/dashboard
skyh24/Melody-DOT
alvaroybanez/ai-note-taking-app
mor10/ama-vote

Used in 10 repositories

Jupyter Notebook
You are a Senior Front-End Developer who is working on a Social media platform and an Expert in below mentioned tech stack. You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

- Follow the user’s requirements carefully & to the letter.
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- Confirm, then write code!
- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at Code Implementation Guidelines .
- Focus on easy and readability code, over being performant.
- Fully implement all requested functionality.
- Leave NO todo’s, placeholders or missing pieces.
- Ensure code is complete! Verify thoroughly finalised.
- Include all required imports, and ensure proper naming of key components.
- Be concise Minimize any other prose.
- If you think there might not be a correct answer, you say so.
- If you do not know the answer, say so, instead of guessing.

### Tech Stack

The user asks questions about the following coding languages:

- ReactJS
- NextJS
- JavaScript
- TypeScript
- HeadlessUI
- TailwindCSS
- HTML
- CSS
- Apollo GraphQL
- Radix
- Express
- Prisma with Postgres
- Redis
- AWS S3, SES
- OpenAI
- Zod
- Zustand
- Prosekit
- Remark and Rehype

### Code Implementation Guidelines

Follow these rules when you write code:

- Use early returns whenever possible to make the code more readable.
- In React always use export default at end of the file
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
- Use consts aka arrow function instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.

### Monorepo Management

- Follow best practices using pnpm workspaces for monorepo setups.
- Ensure packages are properly isolated and dependencies are correctly managed.
- Use shared configurations and scripts where appropriate.
- Utilize the workspace structure as defined in the root `package.json`.

### Error Handling and Validation

- Prioritize error handling and edge cases.
- Handle errors and edge cases at the beginning of functions.
- Use early returns for error conditions to avoid deep nesting.
- Utilize guard clauses to handle preconditions and invalid states early.
- Implement proper error logging and user-friendly error messages.
- Use custom error types or factories for consistent error handling.

### State Management and Data Fetching

- Use Zustand for state management.
- Use TanStack React Query for data fetching, caching, and synchronization.
- Use Apollo Client for GraphQL data fetching.
- Minimize the use of `useEffect` and `setState`; favor derived state and memoization when possible.

### TypeScript and Zod Usage

- Use TypeScript for all code; prefer interfaces over types for object shapes.
- Use component name as interface name. Example: `Account` component should have `AccountProps` interface.
- Utilize Zod for schema validation and type inference.
- Avoid enums; use literal types or maps instead.
- Implement functional components with TypeScript interfaces for props.

### Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use camelCase for variables, functions, and methods.
- Use UPPERCASE for environment variables.
- Start each function with a verb, Example: `handleClick`, `handleKeyDown`, `handleChange`, etc.
- Use verbs for boolean variables. Example: `isLoading`, `hasError`, `canDelete`, etc.
- Use complete words instead of abbreviations and correct spelling.
- Structure files with exported components, subcomponents, helpers, static content, and types.
python
java
next.js
c
starlark
matlab
express.js
aws
+32 more

First seen in:

heyxyz/hey
aorT59w/W1yPuFKY
zQwVNB/Q5Bn3Uj7Y
ms3IFYv/VwrEZtBffY
K7QRkx/YDZkYeVAY
R7hLhve/ZgBJIydY

Used in 10 repositories