Compare commits

..
1 Commits
Author SHA1 Message Date
Iuliia Shnai 4f95f0b54d feat: two emails for abandoned checkout 2026-01-29 14:15:14 +11:00
250 changed files with 4697 additions and 29021 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,136 +0,0 @@
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 57 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |
## Quick Reference
### 1. Eliminating Waterfalls (CRITICAL)
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### 2. Bundle Size Optimization (CRITICAL)
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### 3. Server-Side Performance (HIGH)
- `server-auth-actions` - Authenticate server actions like API routes
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-dedup-props` - Avoid duplicate serialization in RSC props
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-after-nonblocking` - Use after() for non-blocking operations
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners
- `client-passive-event-listeners` - Use passive listeners for scroll
- `client-localstorage-schema` - Version and minimize localStorage data
### 5. Re-render Optimization (MEDIUM)
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-memo-with-default-value` - Hoist default non-primitive props
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-derived-state-no-effect` - Derive state during render, not effects
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
- `rerender-transitions` - Use startTransition for non-urgent updates
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
### 6. Rendering Performance (MEDIUM)
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals
- `rendering-usetransition-loading` - Prefer useTransition for loading state
### 7. JavaScript Performance (LOW-MEDIUM)
- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability
### 8. Advanced Patterns (LOW)
- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-init-once` - Initialize app once per app load
- `advanced-use-latest` - useLatest for stable callback refs
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/async-parallel.md
rules/bundle-barrel-imports.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
@@ -1,55 +0,0 @@
---
title: Store Event Handlers in Refs
impact: LOW
impactDescription: stable subscriptions
tags: advanced, hooks, refs, event-handlers, optimization
---
## Store Event Handlers in Refs
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
**Incorrect (re-subscribes on every render):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
```
**Correct (stable subscription):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
const handlerRef = useRef(handler)
useEffect(() => {
handlerRef.current = handler
}, [handler])
useEffect(() => {
const listener = (e) => handlerRef.current(e)
window.addEventListener(event, listener)
return () => window.removeEventListener(event, listener)
}, [event])
}
```
**Alternative: use `useEffectEvent` if you're on latest React:**
```tsx
import { useEffectEvent } from 'react'
function useWindowEvent(event: string, handler: (e) => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
```
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
@@ -1,42 +0,0 @@
---
title: Initialize App Once, Not Per Mount
impact: LOW-MEDIUM
impactDescription: avoids duplicate init in development
tags: initialization, useEffect, app-startup, side-effects
---
## Initialize App Once, Not Per Mount
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
@@ -1,39 +0,0 @@
---
title: useEffectEvent for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useEffectEvent, refs, optimization
---
## useEffectEvent for Stable Callback Refs
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
**Incorrect (effect re-runs on every callback change):**
```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300)
return () => clearTimeout(timeout)
}, [query, onSearch])
}
```
**Correct (using React's useEffectEvent):**
```tsx
import { useEffectEvent } from 'react';
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchEvent = useEffectEvent(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300)
return () => clearTimeout(timeout)
}, [query])
}
```
@@ -1,38 +0,0 @@
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---
## Prevent Waterfall Chains in API Routes
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
**Incorrect (config waits for auth, data waits for both):**
```typescript
export async function GET(request: Request) {
const session = await auth()
const config = await fetchConfig()
const data = await fetchData(session.user.id)
return Response.json({ data, config })
}
```
**Correct (auth and config start immediately):**
```typescript
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id)
])
return Response.json({ data, config })
}
```
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
@@ -1,80 +0,0 @@
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---
## Defer Await Until Needed
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
**Incorrect (blocks both branches):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true }
}
// Only this branch uses userData
return processUserData(userData)
}
```
**Correct (only blocks when needed):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true }
}
// Fetch only when needed
const userData = await fetchUserData(userId)
return processUserData(userData)
}
```
**Another example (early return optimization):**
```typescript
// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
const permissions = await fetchPermissions(userId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
```
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
@@ -1,51 +0,0 @@
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---
## Dependency-Based Parallelization
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
**Incorrect (profile waits for config unnecessarily):**
```typescript
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
```
**Correct (config and profile run in parallel):**
```typescript
import { all } from 'better-all'
const { user, config, profile } = await all({
async user() { return fetchUser() },
async config() { return fetchConfig() },
async profile() {
return fetchProfile((await this.$.user).id)
}
})
```
**Alternative without extra dependencies:**
We can also create all the promises first, and do `Promise.all()` at the end.
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
@@ -1,28 +0,0 @@
---
title: Promise.all() for Independent Operations
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, promises, waterfalls
---
## Promise.all() for Independent Operations
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
**Incorrect (sequential execution, 3 round trips):**
```typescript
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
```
**Correct (parallel execution, 1 round trip):**
```typescript
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
```
@@ -1,99 +0,0 @@
---
title: Strategic Suspense Boundaries
impact: HIGH
impactDescription: faster initial paint
tags: async, suspense, streaming, layout-shift
---
## Strategic Suspense Boundaries
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
**Incorrect (wrapper blocked by data fetching):**
```tsx
async function Page() {
const data = await fetchData() // Blocks entire page
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
```
The entire layout waits for data even though only the middle section needs it.
**Correct (wrapper shows immediately, data streams in):**
```tsx
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
async function DataDisplay() {
const data = await fetchData() // Only blocks this component
return <div>{data.content}</div>
}
```
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
**Alternative (share promise across components):**
```tsx
function Page() {
// Start fetch immediately, but don't await
const dataPromise = fetchData()
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
)
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Unwraps the promise
return <div>{data.content}</div>
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Reuses the same promise
return <div>{data.summary}</div>
}
```
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
**When NOT to use this pattern:**
- Critical data needed for layout decisions (affects positioning)
- SEO-critical content above the fold
- Small, fast queries where suspense overhead isn't worth it
- When you want to avoid layout shift (loading → content jump)
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
@@ -1,59 +0,0 @@
---
title: Avoid Barrel File Imports
impact: CRITICAL
impactDescription: 200-800ms import cost, slow builds
tags: bundle, imports, tree-shaking, barrel-files, performance
---
## Avoid Barrel File Imports
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
**Incorrect (imports entire library):**
```tsx
import { Check, X, Menu } from 'lucide-react'
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start
import { Button, TextField } from '@mui/material'
// Loads 2,225 modules, takes ~4.2s extra in dev
```
**Correct (imports only what you need):**
```tsx
import Check from 'lucide-react/dist/esm/icons/check'
import X from 'lucide-react/dist/esm/icons/x'
import Menu from 'lucide-react/dist/esm/icons/menu'
// Loads only 3 modules (~2KB vs ~1MB)
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
```
**Alternative (Next.js 13.5+):**
```js
// next.config.js - use optimizePackageImports
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
// Then you can keep the ergonomic barrel imports:
import { Check, X, Menu } from 'lucide-react'
// Automatically transformed to direct imports at build time
```
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
@@ -1,31 +0,0 @@
---
title: Conditional Module Loading
impact: HIGH
impactDescription: loads large data only when needed
tags: bundle, conditional-loading, lazy-loading
---
## Conditional Module Loading
Load large data or modules only when a feature is activated.
**Example (lazy-load animation frames):**
```tsx
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
const [frames, setFrames] = useState<Frame[] | null>(null)
useEffect(() => {
if (enabled && !frames && typeof window !== 'undefined') {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames, setEnabled])
if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}
```
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
@@ -1,49 +0,0 @@
---
title: Defer Non-Critical Third-Party Libraries
impact: MEDIUM
impactDescription: loads after hydration
tags: bundle, third-party, analytics, defer
---
## Defer Non-Critical Third-Party Libraries
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
**Incorrect (blocks initial bundle):**
```tsx
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
**Correct (loads after hydration):**
```tsx
import dynamic from 'next/dynamic'
const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
@@ -1,35 +0,0 @@
---
title: Dynamic Imports for Heavy Components
impact: CRITICAL
impactDescription: directly affects TTI and LCP
tags: bundle, dynamic-import, code-splitting, next-dynamic
---
## Dynamic Imports for Heavy Components
Use `next/dynamic` to lazy-load large components not needed on initial render.
**Incorrect (Monaco bundles with main chunk ~300KB):**
```tsx
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
**Correct (Monaco loads on demand):**
```tsx
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
() => import('./monaco-editor').then(m => m.MonacoEditor),
{ ssr: false }
)
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
@@ -1,50 +0,0 @@
---
title: Preload Based on User Intent
impact: MEDIUM
impactDescription: reduces perceived latency
tags: bundle, preload, user-intent, hover
---
## Preload Based on User Intent
Preload heavy bundles before they're needed to reduce perceived latency.
**Example (preload on hover/focus):**
```tsx
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== 'undefined') {
void import('./monaco-editor')
}
}
return (
<button
onMouseEnter={preload}
onFocus={preload}
onClick={onClick}
>
Open Editor
</button>
)
}
```
**Example (preload when feature flag is enabled):**
```tsx
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled && typeof window !== 'undefined') {
void import('./monaco-editor').then(mod => mod.init())
}
}, [flags.editorEnabled])
return <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
@@ -1,74 +0,0 @@
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---
## Deduplicate Global Event Listeners
Use `useSWRSubscription()` to share global event listeners across component instances.
**Incorrect (N instances = N listeners):**
```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [key, callback])
}
```
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
**Correct (N instances = 1 listener):**
```tsx
import useSWRSubscription from 'swr/subscription'
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set())
}
keyCallbacks.get(key)!.add(callback)
return () => {
const set = keyCallbacks.get(key)
if (set) {
set.delete(callback)
if (set.size === 0) {
keyCallbacks.delete(key)
}
}
}
}, [key, callback])
useSWRSubscription('global-keydown', () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach(cb => cb())
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
})
}
function Profile() {
// Multiple shortcuts will share the same listener
useKeyboardShortcut('p', () => { /* ... */ })
useKeyboardShortcut('k', () => { /* ... */ })
// ...
}
```
@@ -1,71 +0,0 @@
---
title: Version and Minimize localStorage Data
impact: MEDIUM
impactDescription: prevents schema conflicts, reduces storage size
tags: client, localStorage, storage, versioning, data-minimization
---
## Version and Minimize localStorage Data
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
**Incorrect:**
```typescript
// No version, stores everything, no error handling
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
const data = localStorage.getItem('userConfig')
```
**Correct:**
```typescript
const VERSION = 'v2'
function saveConfig(config: { theme: string; language: string }) {
try {
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
} catch {
// Throws in incognito/private browsing, quota exceeded, or disabled
}
}
function loadConfig() {
try {
const data = localStorage.getItem(`userConfig:${VERSION}`)
return data ? JSON.parse(data) : null
} catch {
return null
}
}
// Migration from v1 to v2
function migrate() {
try {
const v1 = localStorage.getItem('userConfig:v1')
if (v1) {
const old = JSON.parse(v1)
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
localStorage.removeItem('userConfig:v1')
}
} catch {}
}
```
**Store minimal fields from server responses:**
```typescript
// User object has 20+ fields, only store what UI needs
function cachePrefs(user: FullUser) {
try {
localStorage.setItem('prefs:v1', JSON.stringify({
theme: user.preferences.theme,
notifications: user.preferences.notifications
}))
} catch {}
}
```
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
@@ -1,48 +0,0 @@
---
title: Use Passive Event Listeners for Scrolling Performance
impact: MEDIUM
impactDescription: eliminates scroll delay caused by event listeners
tags: client, event-listeners, scrolling, performance, touch, wheel
---
## Use Passive Event Listeners for Scrolling Performance
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
**Incorrect:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch)
document.addEventListener('wheel', handleWheel)
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Correct:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch, { passive: true })
document.addEventListener('wheel', handleWheel, { passive: true })
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
@@ -1,56 +0,0 @@
---
title: Use SWR for Automatic Deduplication
impact: MEDIUM-HIGH
impactDescription: automatic deduplication
tags: client, swr, deduplication, data-fetching
---
## Use SWR for Automatic Deduplication
SWR enables request deduplication, caching, and revalidation across component instances.
**Incorrect (no deduplication, each instance fetches):**
```tsx
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
```
**Correct (multiple instances share one request):**
```tsx
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
```
**For immutable data:**
```tsx
import { useImmutableSWR } from '@/lib/swr'
function StaticContent() {
const { data } = useImmutableSWR('/api/config', fetcher)
}
```
**For mutations:**
```tsx
import { useSWRMutation } from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
@@ -1,107 +0,0 @@
---
title: Avoid Layout Thrashing
impact: MEDIUM
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
tags: javascript, dom, css, performance, reflow, layout-thrashing
---
## Avoid Layout Thrashing
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
```
**Incorrect (interleaved reads and writes force reflows):**
```typescript
function layoutThrashing(element: HTMLElement) {
element.style.width = '100px'
const width = element.offsetWidth // Forces reflow
element.style.height = '200px'
const height = element.offsetHeight // Forces another reflow
}
```
**Correct (batch writes, then read once):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect()
}
```
**Correct (batch reads, then writes):**
```typescript
function avoidThrashing(element: HTMLElement) {
// Read phase - all layout queries first
const rect1 = element.getBoundingClientRect()
const offsetWidth = element.offsetWidth
const offsetHeight = element.offsetHeight
// Write phase - all style changes after
element.style.width = '100px'
element.style.height = '200px'
}
```
**Better: use CSS classes**
```css
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
```
```typescript
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
const { width, height } = element.getBoundingClientRect()
}
```
**React example:**
```tsx
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
const width = ref.current.offsetWidth // Forces layout
ref.current.style.height = '200px'
}
}, [isHighlighted])
return <div ref={ref}>Content</div>
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return (
<div className={isHighlighted ? 'highlighted-box' : ''}>
Content
</div>
)
}
```
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
@@ -1,80 +0,0 @@
---
title: Cache Repeated Function Calls
impact: MEDIUM
impactDescription: avoid redundant computation
tags: javascript, cache, memoization, performance
---
## Cache Repeated Function Calls
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
**Incorrect (redundant computation):**
```typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Correct (cached results):**
```typescript
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Simpler pattern for single-value functions:**
```typescript
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
@@ -1,28 +0,0 @@
---
title: Cache Property Access in Loops
impact: LOW-MEDIUM
impactDescription: reduces lookups
tags: javascript, loops, optimization, caching
---
## Cache Property Access in Loops
Cache object property lookups in hot paths.
**Incorrect (3 lookups × N iterations):**
```typescript
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value)
}
```
**Correct (1 lookup total):**
```typescript
const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
process(value)
}
```
@@ -1,70 +0,0 @@
---
title: Cache Storage API Calls
impact: LOW-MEDIUM
impactDescription: reduces expensive I/O
tags: javascript, localStorage, storage, caching, performance
---
## Cache Storage API Calls
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
**Incorrect (reads storage on every call):**
```typescript
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads
```
**Correct (Map cache):**
```typescript
const storageCache = new Map<string, string | null>()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
**Cookie caching:**
```typescript
let cookieCache: Record<string, string> | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
```
**Important (invalidate on external changes):**
If storage can change externally (another tab, server-set cookies), invalidate cache:
```typescript
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})
```
@@ -1,32 +0,0 @@
---
title: Combine Multiple Array Iterations
impact: LOW-MEDIUM
impactDescription: reduces iterations
tags: javascript, arrays, loops, performance
---
## Combine Multiple Array Iterations
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
**Incorrect (3 iterations):**
```typescript
const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)
```
**Correct (1 iteration):**
```typescript
const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []
for (const user of users) {
if (user.isAdmin) admins.push(user)
if (user.isTester) testers.push(user)
if (!user.isActive) inactive.push(user)
}
```
@@ -1,50 +0,0 @@
---
title: Early Return from Functions
impact: LOW-MEDIUM
impactDescription: avoids unnecessary computation
tags: javascript, functions, optimization, early-return
---
## Early Return from Functions
Return early when result is determined to skip unnecessary processing.
**Incorrect (processes all items even after finding answer):**
```typescript
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError = true
errorMessage = 'Name required'
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
```
**Correct (returns immediately on first error):**
```typescript
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
```
@@ -1,45 +0,0 @@
---
title: Hoist RegExp Creation
impact: LOW-MEDIUM
impactDescription: avoids recreation
tags: javascript, regexp, optimization, memoization
---
## Hoist RegExp Creation
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
**Incorrect (new RegExp every render):**
```tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Correct (memoize or hoist):**
```tsx
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Warning (global regex has mutable state):**
Global regex (`/g`) has mutable `lastIndex` state:
```typescript
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0
```
@@ -1,37 +0,0 @@
---
title: Build Index Maps for Repeated Lookups
impact: LOW-MEDIUM
impactDescription: 1M ops to 2K ops
tags: javascript, map, indexing, optimization, performance
---
## Build Index Maps for Repeated Lookups
Multiple `.find()` calls by the same key should use a Map.
**Incorrect (O(n) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
return orders.map(order => ({
...order,
user: users.find(u => u.id === order.userId)
}))
}
```
**Correct (O(1) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map(u => [u.id, u]))
return orders.map(order => ({
...order,
user: userById.get(order.userId)
}))
}
```
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
@@ -1,49 +0,0 @@
---
title: Early Length Check for Array Comparisons
impact: MEDIUM-HIGH
impactDescription: avoids expensive operations when lengths differ
tags: javascript, arrays, performance, optimization, comparison
---
## Early Length Check for Array Comparisons
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join()
}
```
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
@@ -1,82 +0,0 @@
---
title: Use Loop for Min/Max Instead of Sort
impact: LOW
impactDescription: O(n) instead of O(n log n)
tags: javascript, arrays, performance, sorting, algorithms
---
## Use Loop for Min/Max Instead of Sort
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
```typescript
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}
```
Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
```typescript
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}
```
Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
```typescript
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
@@ -1,24 +0,0 @@
---
title: Use Set/Map for O(1) Lookups
impact: LOW-MEDIUM
impactDescription: O(n) to O(1)
tags: javascript, set, map, data-structures, performance
---
## Use Set/Map for O(1) Lookups
Convert arrays to Set/Map for repeated membership checks.
**Incorrect (O(n) per check):**
```typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
```
**Correct (O(1) per check):**
```typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
```
@@ -1,57 +0,0 @@
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
```
**Other immutable array methods:**
- `.toSorted()` - immutable sort
- `.toReversed()` - immutable reverse
- `.toSpliced()` - immutable splice
- `.with()` - immutable element replacement
@@ -1,26 +0,0 @@
---
title: Use Activity Component for Show/Hide
impact: MEDIUM
impactDescription: preserves state/DOM
tags: rendering, activity, visibility, state-preservation
---
## Use Activity Component for Show/Hide
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
**Usage:**
```tsx
import { Activity } from 'react'
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? 'visible' : 'hidden'}>
<ExpensiveMenu />
</Activity>
)
}
```
Avoids expensive re-renders and state loss.
@@ -1,47 +0,0 @@
---
title: Animate SVG Wrapper Instead of SVG Element
impact: LOW
impactDescription: enables hardware acceleration
tags: rendering, svg, css, animation, performance
---
## Animate SVG Wrapper Instead of SVG Element
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
**Incorrect (animating SVG directly - no hardware acceleration):**
```tsx
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
```
**Correct (animating wrapper div - hardware accelerated):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
```
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
@@ -1,40 +0,0 @@
---
title: Use Explicit Conditional Rendering
impact: LOW
impactDescription: prevents rendering 0 or NaN
tags: rendering, conditional, jsx, falsy-values
---
## Use Explicit Conditional Rendering
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
**Incorrect (renders "0" when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count && <span className="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
**Correct (renders nothing when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
@@ -1,38 +0,0 @@
---
title: CSS content-visibility for Long Lists
impact: HIGH
impactDescription: faster initial render
tags: rendering, css, content-visibility, long-lists
---
## CSS content-visibility for Long Lists
Apply `content-visibility: auto` to defer off-screen rendering.
**CSS:**
```css
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
```
**Example:**
```tsx
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map(msg => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
)
}
```
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
@@ -1,46 +0,0 @@
---
title: Hoist Static JSX Elements
impact: LOW
impactDescription: avoids re-creation
tags: rendering, jsx, static, optimization
---
## Hoist Static JSX Elements
Extract static JSX outside components to avoid re-creation.
**Incorrect (recreates element every render):**
```tsx
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />
}
function Container() {
return (
<div>
{loading && <LoadingSkeleton />}
</div>
)
}
```
**Correct (reuses same element):**
```tsx
const loadingSkeleton = (
<div className="animate-pulse h-20 bg-gray-200" />
)
function Container() {
return (
<div>
{loading && loadingSkeleton}
</div>
)
}
```
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
@@ -1,82 +0,0 @@
---
title: Prevent Hydration Mismatch Without Flickering
impact: MEDIUM
impactDescription: avoids visual flicker and hydration errors
tags: rendering, ssr, hydration, localStorage, flicker
---
## Prevent Hydration Mismatch Without Flickering
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
**Incorrect (breaks SSR):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem('theme') || 'light'
return (
<div className={theme}>
{children}
</div>
)
}
```
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<div className={theme}>
{children}
</div>
)
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
```
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
@@ -1,30 +0,0 @@
---
title: Suppress Expected Hydration Mismatches
impact: LOW-MEDIUM
impactDescription: avoids noisy hydration warnings for known differences
tags: rendering, hydration, ssr, nextjs
---
## Suppress Expected Hydration Mismatches
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Dont overuse it.
**Incorrect (known mismatch warnings):**
```tsx
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>
}
```
**Correct (suppress expected mismatch only):**
```tsx
function Timestamp() {
return (
<span suppressHydrationWarning>
{new Date().toLocaleString()}
</span>
)
}
```
@@ -1,28 +0,0 @@
---
title: Optimize SVG Precision
impact: LOW
impactDescription: reduces file size
tags: rendering, svg, optimization, svgo
---
## Optimize SVG Precision
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
**Incorrect (excessive precision):**
```svg
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
```
**Correct (1 decimal place):**
```svg
<path d="M 10.3 20.8 L 30.9 40.2" />
```
**Automate with SVGO:**
```bash
npx svgo --precision=1 --multipass icon.svg
```
@@ -1,75 +0,0 @@
---
title: Use useTransition Over Manual Loading States
impact: LOW
impactDescription: reduces re-renders and improves code clarity
tags: rendering, transitions, useTransition, loading, state
---
## Use useTransition Over Manual Loading States
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
**Incorrect (manual loading state):**
```tsx
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const handleSearch = async (value: string) => {
setIsLoading(true)
setQuery(value)
const data = await fetchResults(value)
setResults(data)
setIsLoading(false)
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isLoading && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Correct (useTransition with built-in pending state):**
```tsx
import { useTransition, useState } from 'react'
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
const handleSearch = (value: string) => {
setQuery(value) // Update input immediately
startTransition(async () => {
// Fetch and update results
const data = await fetchResults(value)
setResults(data)
})
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Benefits:**
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
- **Error resilience**: Pending state correctly resets even if the transition throws
- **Better responsiveness**: Keeps the UI responsive during updates
- **Interrupt handling**: New transitions automatically cancel pending ones
Reference: [useTransition](https://react.dev/reference/react/useTransition)
@@ -1,39 +0,0 @@
---
title: Defer State Reads to Usage Point
impact: MEDIUM
impactDescription: avoids unnecessary subscriptions
tags: rerender, searchParams, localStorage, optimization
---
## Defer State Reads to Usage Point
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
**Incorrect (subscribes to all searchParams changes):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const searchParams = useSearchParams()
const handleShare = () => {
const ref = searchParams.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
**Correct (reads on demand, no subscription):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search)
const ref = params.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
@@ -1,45 +0,0 @@
---
title: Narrow Effect Dependencies
impact: LOW
impactDescription: minimizes effect re-runs
tags: rerender, useEffect, dependencies, optimization
---
## Narrow Effect Dependencies
Specify primitive dependencies instead of objects to minimize effect re-runs.
**Incorrect (re-runs on any user field change):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user])
```
**Correct (re-runs only when id changes):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user.id])
```
**For derived state, compute outside effect:**
```tsx
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode()
}
}, [width])
// Correct: runs only on boolean transition
const isMobile = width < 768
useEffect(() => {
if (isMobile) {
enableMobileMode()
}
}, [isMobile])
```
@@ -1,40 +0,0 @@
---
title: Calculate Derived State During Rendering
impact: MEDIUM
impactDescription: avoids redundant renders and state drift
tags: rerender, derived-state, useEffect, state
---
## Calculate Derived State During Rendering
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
**Incorrect (redundant state and effect):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const [fullName, setFullName] = useState('')
useEffect(() => {
setFullName(firstName + ' ' + lastName)
}, [firstName, lastName])
return <p>{fullName}</p>
}
```
**Correct (derive during render):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const fullName = firstName + ' ' + lastName
return <p>{fullName}</p>
}
```
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
@@ -1,29 +0,0 @@
---
title: Subscribe to Derived State
impact: MEDIUM
impactDescription: reduces re-render frequency
tags: rerender, derived-state, media-query, optimization
---
## Subscribe to Derived State
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
**Incorrect (re-renders on every pixel change):**
```tsx
function Sidebar() {
const width = useWindowWidth() // updates continuously
const isMobile = width < 768
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
**Correct (re-renders only when boolean changes):**
```tsx
function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
@@ -1,74 +0,0 @@
---
title: Use Functional setState Updates
impact: MEDIUM
impactDescription: prevents stale closures and unnecessary callback recreations
tags: react, hooks, useState, useCallback, callbacks, closures
---
## Use Functional setState Updates
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
**Incorrect (requires state as dependency):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items]) // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter(item => item.id !== id))
}, []) // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
**Correct (stable callbacks, no stale closures):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, []) // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems(curr => curr.filter(item => item.id !== id))
}, []) // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
**Benefits:**
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
**When to use functional updates:**
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
**When direct updates are fine:**
- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
@@ -1,58 +0,0 @@
---
title: Use Lazy State Initialization
impact: MEDIUM
impactDescription: wasted computation on every render
tags: react, hooks, useState, performance, initialization
---
## Use Lazy State Initialization
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
**Incorrect (runs on every render):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
const [query, setQuery] = useState('')
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs on every render
const [settings, setSettings] = useState(
JSON.parse(localStorage.getItem('settings') || '{}')
)
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
**Correct (runs only once):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
const [query, setQuery] = useState('')
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs only on initial render
const [settings, setSettings] = useState(() => {
const stored = localStorage.getItem('settings')
return stored ? JSON.parse(stored) : {}
})
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
@@ -1,38 +0,0 @@
---
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
impact: MEDIUM
impactDescription: restores memoization by using a constant for default value
tags: rerender, memo, optimization
---
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
To address this issue, extract the default value into a constant.
**Incorrect (`onClick` has different values on every rerender):**
```tsx
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
**Correct (stable default value):**
```tsx
const NOOP = () => {};
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
@@ -1,44 +0,0 @@
---
title: Extract to Memoized Components
impact: MEDIUM
impactDescription: enables early returns
tags: rerender, memo, useMemo, optimization
---
## Extract to Memoized Components
Extract expensive work into memoized components to enable early returns before computation.
**Incorrect (computes avatar even when loading):**
```tsx
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user)
return <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
@@ -1,45 +0,0 @@
---
title: Put Interaction Logic in Event Handlers
impact: MEDIUM
impactDescription: avoids effect re-runs and duplicate side effects
tags: rerender, useEffect, events, side-effects, dependencies
---
## Put Interaction Logic in Event Handlers
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
**Incorrect (event modeled as state + effect):**
```tsx
function Form() {
const [submitted, setSubmitted] = useState(false)
const theme = useContext(ThemeContext)
useEffect(() => {
if (submitted) {
post('/api/register')
showToast('Registered', theme)
}
}, [submitted, theme])
return <button onClick={() => setSubmitted(true)}>Submit</button>
}
```
**Correct (do it in the handler):**
```tsx
function Form() {
const theme = useContext(ThemeContext)
function handleSubmit() {
post('/api/register')
showToast('Registered', theme)
}
return <button onClick={handleSubmit}>Submit</button>
}
```
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
@@ -1,35 +0,0 @@
---
title: Do not wrap a simple expression with a primitive result type in useMemo
impact: LOW-MEDIUM
impactDescription: wasted computation on every render
tags: rerender, useMemo, optimization
---
## Do not wrap a simple expression with a primitive result type in useMemo
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
**Incorrect:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = useMemo(() => {
return user.isLoading || notifications.isLoading
}, [user.isLoading, notifications.isLoading])
if (isLoading) return <Skeleton />
// return some markup
}
```
**Correct:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = user.isLoading || notifications.isLoading
if (isLoading) return <Skeleton />
// return some markup
}
```
@@ -1,40 +0,0 @@
---
title: Use Transitions for Non-Urgent Updates
impact: MEDIUM
impactDescription: maintains UI responsiveness
tags: rerender, transitions, startTransition, performance
---
## Use Transitions for Non-Urgent Updates
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
**Incorrect (blocks UI on every scroll):**
```tsx
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => setScrollY(window.scrollY)
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
**Correct (non-blocking updates):**
```tsx
import { startTransition } from 'react'
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY))
}
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
@@ -1,73 +0,0 @@
---
title: Use useRef for Transient Values
impact: MEDIUM
impactDescription: avoids unnecessary re-renders on frequent updates
tags: rerender, useref, state, performance
---
## Use useRef for Transient Values
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
**Incorrect (renders every update):**
```tsx
function Tracker() {
const [lastX, setLastX] = useState(0)
useEffect(() => {
const onMove = (e: MouseEvent) => setLastX(e.clientX)
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
style={{
position: 'fixed',
top: 0,
left: lastX,
width: 8,
height: 8,
background: 'black',
}}
/>
)
}
```
**Correct (no re-render for tracking):**
```tsx
function Tracker() {
const lastXRef = useRef(0)
const dotRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const onMove = (e: MouseEvent) => {
lastXRef.current = e.clientX
const node = dotRef.current
if (node) {
node.style.transform = `translateX(${e.clientX}px)`
}
}
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
ref={dotRef}
style={{
position: 'fixed',
top: 0,
left: 0,
width: 8,
height: 8,
background: 'black',
transform: 'translateX(0px)',
}}
/>
)
}
```
@@ -1,73 +0,0 @@
---
title: Use after() for Non-Blocking Operations
impact: MEDIUM
impactDescription: faster response times
tags: server, async, logging, analytics, side-effects
---
## Use after() for Non-Blocking Operations
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
**Incorrect (blocks response):**
```tsx
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Logging blocks the response
const userAgent = request.headers.get('user-agent') || 'unknown'
await logUserAction({ userAgent })
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
**Correct (non-blocking):**
```tsx
import { after } from 'next/server'
import { headers, cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Log after response is sent
after(async () => {
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
logUserAction({ sessionCookie, userAgent })
})
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
The response is sent immediately while logging happens in the background.
**Common use cases:**
- Analytics tracking
- Audit logging
- Sending notifications
- Cache invalidation
- Cleanup tasks
**Important notes:**
- `after()` runs even if the response fails or redirects
- Works in Server Actions, Route Handlers, and Server Components
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
@@ -1,96 +0,0 @@
---
title: Authenticate Server Actions Like API Routes
impact: CRITICAL
impactDescription: prevents unauthorized access to server mutations
tags: server, server-actions, authentication, security, authorization
---
## Authenticate Server Actions Like API Routes
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
**Incorrect (no authentication check):**
```typescript
'use server'
export async function deleteUser(userId: string) {
// Anyone can call this! No auth check
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**Correct (authentication inside the action):**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { unauthorized } from '@/lib/errors'
export async function deleteUser(userId: string) {
// Always check auth inside the action
const session = await verifySession()
if (!session) {
throw unauthorized('Must be logged in')
}
// Check authorization too
if (session.user.role !== 'admin' && session.user.id !== userId) {
throw unauthorized('Cannot delete other users')
}
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**With input validation:**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { z } from 'zod'
const updateProfileSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email()
})
export async function updateProfile(data: unknown) {
// Validate input first
const validated = updateProfileSchema.parse(data)
// Then authenticate
const session = await verifySession()
if (!session) {
throw new Error('Unauthorized')
}
// Then authorize
if (session.user.id !== validated.userId) {
throw new Error('Can only update own profile')
}
// Finally perform the mutation
await db.user.update({
where: { id: validated.userId },
data: {
name: validated.name,
email: validated.email
}
})
return { success: true }
}
```
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
@@ -1,41 +0,0 @@
---
title: Cross-Request LRU Caching
impact: HIGH
impactDescription: caches across requests
tags: server, cache, lru, cross-request
---
## Cross-Request LRU Caching
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
**Implementation:**
```typescript
import { LRUCache } from 'lru-cache'
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 5 * 60 * 1000 // 5 minutes
})
export async function getUser(id: string) {
const cached = cache.get(id)
if (cached) return cached
const user = await db.user.findUnique({ where: { id } })
cache.set(id, user)
return user
}
// Request 1: DB query, result cached
// Request 2: cache hit, no DB query
```
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
@@ -1,76 +0,0 @@
---
title: Per-Request Deduplication with React.cache()
impact: MEDIUM
impactDescription: deduplicates within request
tags: server, cache, react-cache, deduplication
---
## Per-Request Deduplication with React.cache()
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
**Usage:**
```typescript
import { cache } from 'react'
export const getCurrentUser = cache(async () => {
const session = await auth()
if (!session?.user?.id) return null
return await db.user.findUnique({
where: { id: session.user.id }
})
})
```
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
**Avoid inline objects as arguments:**
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
**Incorrect (always cache miss):**
```typescript
const getUser = cache(async (params: { uid: number }) => {
return await db.user.findUnique({ where: { id: params.uid } })
})
// Each call creates new object, never hits cache
getUser({ uid: 1 })
getUser({ uid: 1 }) // Cache miss, runs query again
```
**Correct (cache hit):**
```typescript
const getUser = cache(async (uid: number) => {
return await db.user.findUnique({ where: { id: uid } })
})
// Primitive args use value equality
getUser(1)
getUser(1) // Cache hit, returns cached result
```
If you must pass objects, pass the same reference:
```typescript
const params = { uid: 1 }
getUser(params) // Query runs
getUser(params) // Cache hit (same reference)
```
**Next.js-Specific Note:**
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
- Database queries (Prisma, Drizzle, etc.)
- Heavy computations
- Authentication checks
- File system operations
- Any non-fetch async work
Use `React.cache()` to deduplicate these operations across your component tree.
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
@@ -1,65 +0,0 @@
---
title: Avoid Duplicate Serialization in RSC Props
impact: LOW
impactDescription: reduces network payload by avoiding duplicate serialization
tags: server, rsc, serialization, props, client-components
---
## Avoid Duplicate Serialization in RSC Props
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
**Incorrect (duplicates array):**
```tsx
// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
```
**Correct (sends 3 strings):**
```tsx
// RSC: send once
<ClientList usernames={usernames} />
// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])
```
**Nested deduplication behavior:**
Deduplication works recursively. Impact varies by data type:
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
```tsx
// string[] - duplicates everything
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
// object[] - duplicates array structure only
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
```
**Operations breaking deduplication (create new references):**
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
**More examples:**
```tsx
// ❌ Bad
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />
// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client
```
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
@@ -1,83 +0,0 @@
---
title: Parallel Data Fetching with Component Composition
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, composition
---
## Parallel Data Fetching with Component Composition
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
**Incorrect (Sidebar waits for Page's fetch to complete):**
```tsx
export default async function Page() {
const header = await fetchHeader()
return (
<div>
<div>{header}</div>
<Sidebar />
</div>
)
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
```
**Correct (both fetch simultaneously):**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
export default function Page() {
return (
<div>
<Header />
<Sidebar />
</div>
)
}
```
**Alternative with children prop:**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
function Layout({ children }: { children: ReactNode }) {
return (
<div>
<Header />
{children}
</div>
)
}
export default function Page() {
return (
<Layout>
<Sidebar />
</Layout>
)
}
```
@@ -1,38 +0,0 @@
---
title: Minimize Serialization at RSC Boundaries
impact: HIGH
impactDescription: reduces data transfer size
tags: server, rsc, serialization, props
---
## Minimize Serialization at RSC Boundaries
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
**Incorrect (serializes all 50 fields):**
```tsx
async function Page() {
const user = await fetchUser() // 50 fields
return <Profile user={user} />
}
'use client'
function Profile({ user }: { user: User }) {
return <div>{user.name}</div> // uses 1 field
}
```
**Correct (serializes only 1 field):**
```tsx
async function Page() {
const user = await fetchUser()
return <Profile name={user.name} />
}
'use client'
function Profile({ name }: { name: string }) {
return <div>{name}</div>
}
```
@@ -1,39 +0,0 @@
---
name: web-design-guidelines
description: Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
metadata:
author: vercel
version: "1.0.0"
argument-hint: <file-or-pattern>
---
# Web Interface Guidelines
Review files for compliance with Web Interface Guidelines.
## How It Works
1. Fetch the latest guidelines from the source URL below
2. Read the specified files (or prompt user for files/pattern)
3. Check against all rules in the fetched guidelines
4. Output findings in the terse `file:line` format
## Guidelines Source
Fetch fresh guidelines before each review:
```
https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/main/command.md
```
Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions.
## Usage
When a user provides a file or pattern argument:
1. Fetch guidelines from the source URL above
2. Read the specified files
3. Apply all rules from the fetched guidelines
4. Output findings using the format specified in the guidelines
If no files specified, ask the user which files to review.
@@ -1,14 +1,18 @@
---
description: Base Guidelines for Claude Opus 4.6 + Cursor Agent
globs: *,**/*
description:
globs:
alwaysApply: true
---
---
description: Base Guidelines for Sonnet-3.7 + Cursor Agent
globs: *,**/*
---
# Instructions
1. Always search with SemanticSearch or Grep first to find existing core files before creating new ones
1. Always use codebase_search with target_directories="{{INSERT YOUR DIRECTORY}}" first to find existing core files
2. Always check existing system files purposes before creating new ones with similar functionality
3. Always list the cursor rules you're using
3. Always list the cursor rules youre using
# Optional
+151 -151
View File
@@ -1,8 +1,12 @@
---
globs: **/trigger/**/*.ts, **/trigger/**/*.tsx,**/trigger/**/*.js,**/trigger/**/*.jsx
description: Guidelines for writing Trigger.dev tasks
description:
globs: **/trigger/**/*.ts, **/trigger/**/*.tsx
alwaysApply: false
---
---
description: Guidelines for writing Trigger.dev tasks
globs: "**/trigger/**/*.ts, **/trigger/**/*.tsx"
---
# How to write Trigger.dev tasks
@@ -10,55 +14,43 @@ alwaysApply: false
1. Run the CLI `init` command: `npx trigger.dev@latest init`.
2. Create a Trigger.dev task.
3. Set up any environment variables.
4. Run the Trigger.dev dev command: `npx trigger.dev@latest dev`.
## Essential requirements when generating task code
1. You MUST use `@trigger.dev/sdk/v3`
2. You MUST NEVER use `client.defineJob`
3. YOU MUST `export` every task, including subtasks
4. If you are able to generate an example payload for a task, do so.
3. Set up environment variables.
4. Run the Trigger.dev command: `npx trigger.dev@latest dev`.
## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨
As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application:
```ts
```typescript
// ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION
client.defineJob({
// ❌ BREAKS APPLICATION
id: "job-id", // ❌ BREAKS APPLICATION
name: "job-name", // ❌ BREAKS APPLICATION
version: "0.0.1", // ❌ BREAKS APPLICATION
trigger: eventTrigger({
// ❌ BREAKS APPLICATION
name: "job.trigger", // ❌ BREAKS APPLICATION
schema: z.object({
// ❌ BREAKS APPLICATION
client.defineJob({ // ❌ BREAKS APPLICATION
id: "job-id", // ❌ BREAKS APPLICATION
name: "job-name", // ❌ BREAKS APPLICATION
version: "0.0.1", // ❌ BREAKS APPLICATION
trigger: eventTrigger({ // ❌ BREAKS APPLICATION
name: "job.trigger", // ❌ BREAKS APPLICATION
schema: z.object({ // ❌ BREAKS APPLICATION
// Input schema here // ❌ BREAKS APPLICATION
}), // ❌ BREAKS APPLICATION
}), // ❌ BREAKS APPLICATION
integrations: {
// ❌ BREAKS APPLICATION
}), // ❌ BREAKS APPLICATION
}), // ❌ BREAKS APPLICATION
integrations: { // ❌ BREAKS APPLICATION
// Integrations here // ❌ BREAKS APPLICATION
}, // ❌ BREAKS APPLICATION
run: async (payload, io) => {
// ❌ BREAKS APPLICATION
// Job logic goes here // ❌ BREAKS APPLICATION
return {
// ❌ BREAKS APPLICATION
}, // ❌ BREAKS APPLICATION
run: async (payload, io) => { // ❌ BREAKS APPLICATION
// Job logic goes here // ❌ BREAKS APPLICATION
return { // ❌ BREAKS APPLICATION
// Return job results // ❌ BREAKS APPLICATION
}; // ❌ BREAKS APPLICATION
}, // ❌ BREAKS APPLICATION
}; // ❌ BREAKS APPLICATION
}, // ❌ BREAKS APPLICATION
});
```
Instead, you MUST ALWAYS generate ONLY this pattern:
```ts
```typescript
// ✅ ALWAYS GENERATE THIS EXACT PATTERN
import { task } from "@trigger.dev/sdk/v3";
//1. You need to export each task, even if it's a subtask
@@ -72,11 +64,18 @@ export const helloWorld = task({
});
```
## ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION
1. You MUST use `@trigger.dev/sdk/v3`
2. You MUST NEVER use `client.defineJob`
3. YOU MUST `export` every task, including subtasks
4. If you are able to generate an example payload for a task, do so.
## Correct Task implementations
A task is a function that can run for a long time with resilience to failure:
```ts
```typescript
import { task } from "@trigger.dev/sdk/v3";
export const helloWorld = task({
@@ -88,7 +87,6 @@ export const helloWorld = task({
```
Key points:
- Tasks must be exported, even subtasks in the same file
- Each task needs a unique ID within your project
- The `run` function contains your task logic
@@ -99,7 +97,7 @@ Key points:
Control retry behavior when errors occur:
```ts
```typescript
export const taskWithRetries = task({
id: "task-with-retries",
retry: {
@@ -119,7 +117,7 @@ export const taskWithRetries = task({
Control concurrency:
```ts
```typescript
export const oneAtATime = task({
id: "one-at-a-time",
queue: {
@@ -135,7 +133,7 @@ export const oneAtATime = task({
Specify CPU/RAM requirements:
```ts
```typescript
export const heavyTask = task({
id: "heavy-task",
machine: {
@@ -149,21 +147,21 @@ export const heavyTask = task({
Machine configuration options:
| Machine name | vCPU | Memory | Disk space |
| ------------------ | ---- | ------ | ---------- |
| micro | 0.25 | 0.25 | 10GB |
| small-1x (default) | 0.5 | 0.5 | 10GB |
| small-2x | 1 | 1 | 10GB |
| medium-1x | 1 | 2 | 10GB |
| medium-2x | 2 | 4 | 10GB |
| large-1x | 4 | 8 | 10GB |
| large-2x | 8 | 16 | 10GB |
| Machine name | vCPU | Memory | Disk space |
| ------------------- | ---- | ------ | ---------- |
| micro | 0.25 | 0.25 | 10GB |
| small-1x (default) | 0.5 | 0.5 | 10GB |
| small-2x | 1 | 1 | 10GB |
| medium-1x | 1 | 2 | 10GB |
| medium-2x | 2 | 4 | 10GB |
| large-1x | 4 | 8 | 10GB |
| large-2x | 8 | 16 | 10GB |
#### Max Duration
Limit how long a task can run:
```ts
```typescript
export const longTask = task({
id: "long-task",
maxDuration: 300, // 5 minutes
@@ -181,7 +179,7 @@ Tasks support several lifecycle hooks:
Runs before each attempt, can return data for other functions:
```ts
```typescript
export const taskWithInit = task({
id: "task-with-init",
init: async (payload, { ctx }) => {
@@ -197,7 +195,7 @@ export const taskWithInit = task({
Runs after each attempt, regardless of success/failure:
```ts
```typescript
export const taskWithCleanup = task({
id: "task-with-cleanup",
cleanup: async (payload, { ctx }) => {
@@ -213,7 +211,7 @@ export const taskWithCleanup = task({
Runs once when a task starts (not on retries):
```ts
```typescript
export const taskWithOnStart = task({
id: "task-with-on-start",
onStart: async (payload, { ctx }) => {
@@ -229,7 +227,7 @@ export const taskWithOnStart = task({
Runs when a task succeeds:
```ts
```typescript
export const taskWithOnSuccess = task({
id: "task-with-on-success",
onSuccess: async (payload, output, { ctx }) => {
@@ -245,7 +243,7 @@ export const taskWithOnSuccess = task({
Runs when a task fails after all retries:
```ts
```typescript
export const taskWithOnFailure = task({
id: "task-with-on-failure",
onFailure: async (payload, error, { ctx }) => {
@@ -261,7 +259,7 @@ export const taskWithOnFailure = task({
Controls error handling and retry behavior:
```ts
```typescript
export const taskWithErrorHandling = task({
id: "task-with-error-handling",
handleError: async (error, { ctx }) => {
@@ -277,7 +275,7 @@ Global lifecycle hooks can also be defined in `trigger.config.ts` to apply to al
## Correct Schedules task (cron) implementations
```ts
```typescript
import { schedules } from "@trigger.dev/sdk/v3";
export const firstScheduledTask = schedules.task({
@@ -318,7 +316,7 @@ export const firstScheduledTask = schedules.task({
### Attach a Declarative schedule
```ts
```typescript
import { schedules } from "@trigger.dev/sdk/v3";
// Sepcify a cron pattern (UTC)
@@ -332,7 +330,7 @@ export const firstScheduledTask = schedules.task({
});
```
```ts
```typescript
import { schedules } from "@trigger.dev/sdk/v3";
// Specify a specific timezone like this:
@@ -352,7 +350,6 @@ export const secondScheduledTask = schedules.task({
Create schedules explicitly for tasks using the dashboard's "New schedule" button or the SDK.
#### Benefits
- Dynamic creation (e.g., one schedule per user)
- Manage without code deployment:
- Activate/disable
@@ -360,16 +357,14 @@ Create schedules explicitly for tasks using the dashboard's "New schedule" butto
- Delete
#### Implementation
1. Define a task using `schedules.task()`
2. Attach one or more schedules via:
- Dashboard
- SDK
1. Define a task using `schedules.task()`
2. Attach one or more schedules via:
- Dashboard
- SDK
#### Attach schedules with the SDK like this
```ts
```typescript
const createdSchedule = await schedules.create({
//The id of the scheduled task you want to attach to.
task: firstScheduledTask.id,
@@ -384,7 +379,7 @@ const createdSchedule = await schedules.create({
Schema tasks validate payloads against a schema before execution:
```ts
```typescript
import { schemaTask } from "@trigger.dev/sdk/v3";
import { z } from "zod";
@@ -409,7 +404,7 @@ When you trigger a task from your backend code, you need to set the `TRIGGER_SEC
Triggers a single run of a task with specified payload and options without importing the task. Use type-only imports for full type checking.
```ts
```typescript
import { tasks } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
@@ -427,7 +422,7 @@ export async function POST(request: Request) {
Triggers multiple runs of a single task with different payloads without importing the task.
```ts
```typescript
import { tasks } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
@@ -435,17 +430,39 @@ export async function POST(request: Request) {
const data = await request.json();
const batchHandle = await tasks.batchTrigger<typeof emailSequence>(
"email-sequence",
data.users.map((u) => ({ payload: { to: u.email, name: u.name } })),
data.users.map((u) => ({ payload: { to: u.email, name: u.name } }))
);
return Response.json(batchHandle);
}
```
### tasks.triggerAndPoll()
Triggers a task and polls until completion. Not recommended for web requests as it blocks until the run completes. Consider using Realtime docs for better alternatives.
```typescript
import { tasks } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
export async function POST(request: Request) {
const data = await request.json();
const result = await tasks.triggerAndPoll<typeof emailSequence>(
"email-sequence",
{
to: data.email,
name: data.name,
},
{ pollIntervalMs: 5000 }
);
return Response.json(result);
}
```
### batch.trigger()
Triggers multiple runs of different tasks at once, useful when you need to execute multiple tasks simultaneously.
```ts
```typescript
import { batch } from "@trigger.dev/sdk/v3";
import type { myTask1, myTask2 } from "~/trigger/myTasks";
@@ -465,7 +482,7 @@ export async function POST(request: Request) {
Triggers a single run of a task with specified payload and options.
```ts
```typescript
import { myOtherTask, runs } from "~/trigger/my-other-task";
export const myTask = task({
@@ -485,15 +502,13 @@ If you need to call `trigger()` on a task in a loop, use `batchTrigger()` instea
Triggers multiple runs of a single task with different payloads.
```ts
import { batch, myOtherTask } from "~/trigger/my-other-task";
```typescript
import { myOtherTask, batch } from "~/trigger/my-other-task";
export const myTask = task({
id: "my-task",
run: async (payload: string) => {
const batchHandle = await myOtherTask.batchTrigger([
{ payload: "some data" },
]);
const batchHandle = await myOtherTask.batchTrigger([{ payload: "some data" }]);
//...do other stuff
const batch = await batch.retrieve(batchHandle.id);
@@ -505,7 +520,7 @@ export const myTask = task({
Triggers a task and waits for the result, useful when you need to call a different task and use its result.
```ts
```typescript
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
@@ -523,7 +538,7 @@ The result object needs to be checked to see if the child task run was successfu
Batch triggers a task and waits for all results, useful for fan-out patterns.
```ts
```typescript
export const batchParentTask = task({
id: "parent-task",
run: async (payload: string) => {
@@ -545,13 +560,11 @@ You can handle run failures by inspecting individual run results and implementin
Batch triggers multiple different tasks and waits for all results.
```ts
```typescript
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
const results = await batch.triggerAndWait<
typeof childTask1 | typeof childTask2
>([
const results = await batch.triggerAndWait<typeof childTask1 | typeof childTask2>([
{ id: "child-task-1", payload: { foo: "World" } },
{ id: "child-task-2", payload: { bar: 42 } },
]);
@@ -576,7 +589,7 @@ export const parentTask = task({
Batch triggers multiple tasks by passing task instances, useful for static task sets.
```ts
```typescript
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
@@ -595,7 +608,7 @@ export const parentTask = task({
Batch triggers multiple tasks by passing task instances and waits for all results.
```ts
```typescript
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
@@ -625,24 +638,24 @@ Metadata allows attaching up to 256KB of structured data to a run, which can be
Add metadata when triggering a task:
```ts
```typescript
const handle = await myTask.trigger(
{ message: "hello world" },
{ metadata: { user: { name: "Eric", id: "user_1234" } } },
{ metadata: { user: { name: "Eric", id: "user_1234" } } }
);
```
Access metadata inside a run:
```ts
import { metadata, task } from "@trigger.dev/sdk/v3";
```typescript
import { task, metadata } from "@trigger.dev/sdk/v3";
export const myTask = task({
id: "my-task",
run: async (payload: { message: string }) => {
// Get the whole metadata object
const currentMetadata = metadata.current();
// Get a specific key
const user = metadata.get("user");
console.log(user.name); // "Eric"
@@ -666,9 +679,8 @@ Metadata can be updated as the run progresses:
Updates can be chained with a fluent API:
```ts
metadata
.set("progress", 0.1)
```typescript
metadata.set("progress", 0.1)
.append("logs", "Step 1 complete")
.increment("progress", 0.4);
```
@@ -677,13 +689,13 @@ metadata
Child tasks can update parent task metadata:
```ts
```typescript
export const childTask = task({
id: "child-task",
run: async (payload: { message: string }) => {
// Update parent task's metadata
metadata.parent.set("progress", 0.5);
// Update root task's metadata
metadata.root.set("status", "processing");
},
@@ -694,7 +706,7 @@ export const childTask = task({
Metadata accepts any JSON-serializable object. For type safety, consider wrapping with Zod:
```ts
```typescript
import { z } from "zod";
const Metadata = z.object({
@@ -727,7 +739,7 @@ Trigger.dev Realtime enables subscribing to runs for real-time updates on run st
Subscribe to a run after triggering a task:
```ts
```typescript
import { runs, tasks } from "@trigger.dev/sdk/v3";
async function myBackend() {
@@ -749,14 +761,13 @@ async function myBackend() {
You can infer types of run's payload and output by passing the task type:
```ts
```typescript
import { runs } from "@trigger.dev/sdk/v3";
import type { myTask } from "./trigger/my-task";
for await (const run of runs.subscribeToRun<typeof myTask>(handle.id)) {
console.log(run.payload.some); // Type-safe access to payload
if (run.output) {
console.log(run.output.result); // Type-safe access to output
}
@@ -767,8 +778,8 @@ for await (const run of runs.subscribeToRun<typeof myTask>(handle.id)) {
Stream data in realtime from inside your tasks using the metadata system:
```ts
import { metadata, task } from "@trigger.dev/sdk/v3";
```typescript
import { task, metadata } from "@trigger.dev/sdk/v3";
import OpenAI from "openai";
export type STREAMS = {
@@ -799,10 +810,8 @@ export const myTask = task({
Subscribe to streams using `withStreams`:
```ts
for await (const part of runs
.subscribeToRun<typeof myTask>(runId)
.withStreams<STREAMS>()) {
```typescript
for await (const part of runs.subscribeToRun<typeof myTask>(runId).withStreams<STREAMS>()) {
switch (part.type) {
case "run": {
console.log("Received run", part.run);
@@ -828,7 +837,7 @@ npm add @trigger.dev/react-hooks
All hooks require a Public Access Token. You can provide it directly to each hook:
```ts
```typescriptx
import { useRealtimeRun } from "@trigger.dev/react-hooks";
function MyComponent({ runId, publicAccessToken }) {
@@ -841,7 +850,7 @@ function MyComponent({ runId, publicAccessToken }) {
Or use the `TriggerAuthContext` provider:
```ts
```typescriptx
import { TriggerAuthContext } from "@trigger.dev/react-hooks";
function SetupTrigger({ publicAccessToken }) {
@@ -855,7 +864,7 @@ function SetupTrigger({ publicAccessToken }) {
For Next.js App Router, wrap the provider in a client component:
```ts
```typescriptx
// components/TriggerProvider.tsx
"use client";
@@ -875,8 +884,7 @@ export function TriggerProvider({ accessToken, children }) {
Several approaches for Next.js App Router:
1. **Using cookies**:
```ts
```typescriptx
// Server action
export async function startRun() {
const handle = await tasks.trigger<typeof exampleTask>("example", { foo: "bar" });
@@ -896,20 +904,16 @@ export default function RunPage({ params }) {
```
2. **Using query parameters**:
```ts
```typescriptx
// Server action
export async function startRun() {
const handle = await tasks.trigger<typeof exampleTask>("example", {
foo: "bar",
});
const handle = await tasks.trigger<typeof exampleTask>("example", { foo: "bar" });
redirect(`/runs/${handle.id}?publicAccessToken=${handle.publicAccessToken}`);
}
```
3. **Server-side token generation**:
```ts
```typescriptx
// Page component
export default async function RunPage({ params }) {
const publicAccessToken = await generatePublicAccessToken(params.id);
@@ -939,7 +943,7 @@ export async function generatePublicAccessToken(runId: string) {
Data fetching hooks that use SWR for caching:
```ts
```typescriptx
"use client";
import { useRun } from "@trigger.dev/react-hooks";
import type { myTask } from "@/trigger/myTask";
@@ -955,7 +959,6 @@ function MyComponent({ runId }) {
```
Common options:
- `revalidateOnFocus`: Revalidate when window regains focus
- `revalidateOnReconnect`: Revalidate when network reconnects
- `refreshInterval`: Polling interval in milliseconds
@@ -970,7 +973,7 @@ For most use cases, Realtime hooks are preferred over SWR hooks with polling due
For client-side usage, generate a public access token with appropriate scopes:
```ts
```typescript
import { auth } from "@trigger.dev/sdk/v3";
const publicToken = await auth.createPublicToken({
@@ -990,7 +993,7 @@ Idempotency ensures that an operation produces the same result when called multi
Provide an `idempotencyKey` when triggering a task to ensure it runs only once with that key:
```ts
```typescript
import { idempotencyKeys, task } from "@trigger.dev/sdk/v3";
export const myTask = task({
@@ -1015,22 +1018,20 @@ export const myTask = task({
By default, keys are scoped to the current run. You can create globally unique keys:
```ts
const idempotencyKey = await idempotencyKeys.create("my-task-key", {
scope: "global",
});
```typescript
const idempotencyKey = await idempotencyKeys.create("my-task-key", { scope: "global" });
```
When triggering from backend code:
```ts
```typescript
const idempotencyKey = await idempotencyKeys.create([myUser.id, "my-task"]);
await tasks.trigger("my-task", { some: "data" }, { idempotencyKey });
```
You can also pass a string directly:
```ts
```typescript
await myTask.trigger({ some: "data" }, { idempotencyKey: myUser.id });
```
@@ -1038,10 +1039,10 @@ await myTask.trigger({ some: "data" }, { idempotencyKey: myUser.id });
The `idempotencyKeyTTL` option defines a time window during which duplicate triggers return the original run:
```ts
```typescript
await childTask.trigger(
{ foo: "bar" },
{ idempotencyKey, idempotencyKeyTTL: "60s" },
{ foo: "bar" },
{ idempotencyKey, idempotencyKeyTTL: "60s" }
);
await wait.for({ seconds: 61 });
@@ -1051,7 +1052,6 @@ await childTask.trigger({ foo: "bar" }, { idempotencyKey });
```
Supported time units:
- `s` for seconds (e.g., `60s`)
- `m` for minutes (e.g., `5m`)
- `h` for hours (e.g., `2h`)
@@ -1061,7 +1061,7 @@ Supported time units:
While not directly supported, you can implement payload-based idempotency by hashing the payload:
```ts
```typescript
import { createHash } from "node:crypto";
const idempotencyKey = await idempotencyKeys.create(hash(payload));
@@ -1083,9 +1083,9 @@ function hash(payload: any): string {
## Correct Logs implementation
```ts
```typescript
// onFailure executes after all retries are exhausted; use for notifications, logging, or side effects on final failure:
import { logger, task } from "@trigger.dev/sdk/v3";
import { task, logger } from "@trigger.dev/sdk/v3";
export const loggingExample = task({
id: "logging-example",
@@ -1100,11 +1100,11 @@ export const loggingExample = task({
});
```
## Correct `trigger.config.ts` implementation
## Correct `trigger.config.ts` implementation
The `trigger.config.ts` file configures your Trigger.dev project, specifying task locations, retry settings, telemetry, and build options.
```ts
```typescript
import { defineConfig } from "@trigger.dev/sdk/v3";
export default defineConfig({
@@ -1129,7 +1129,7 @@ export default defineConfig({
Specify where your tasks are located:
```ts
```typescript
dirs: ["./trigger"],
```
@@ -1139,7 +1139,7 @@ Files with `.test` or `.spec` are automatically excluded, but you can customize
Add global hooks for all tasks:
```ts
```typescript
onStart: async (payload, { ctx }) => {
console.log("Task started", ctx.task.id);
},
@@ -1155,7 +1155,7 @@ onFailure: async (payload, error, { ctx }) => {
Add OpenTelemetry instrumentations for enhanced logging:
```ts
```typescript
telemetry: {
instrumentations: [
new PrismaInstrumentation(),
@@ -1169,7 +1169,7 @@ telemetry: {
Specify the runtime environment:
```ts
```typescript
runtime: "node", // or "bun" (experimental)
```
@@ -1177,7 +1177,7 @@ runtime: "node", // or "bun" (experimental)
Set default machine for all tasks:
```ts
```typescript
defaultMachine: "large-1x",
```
@@ -1185,7 +1185,7 @@ defaultMachine: "large-1x",
Configure logging verbosity:
```ts
```typescript
logLevel: "debug", // Controls logger API logs
```
@@ -1193,7 +1193,7 @@ logLevel: "debug", // Controls logger API logs
Set default maximum runtime for all tasks:
```ts
```typescript
maxDuration: 60, // 60 seconds
```
@@ -1201,7 +1201,7 @@ maxDuration: 60, // 60 seconds
Customize the build process:
```ts
```typescript
build: {
external: ["header-generator"], // Don't bundle these packages
jsx: {
@@ -1245,11 +1245,11 @@ You can also create custom build extensions with hooks like `onBuildStart`, `onB
#### Trigger with:
```ts
```typescript
await myTask.trigger({ name: "Alice", age: 30 });
```
## AI model verification steps
## AI MODEL VERIFICATION STEPS
Before generating any code, you MUST verify:
@@ -1257,7 +1257,7 @@ Before generating any code, you MUST verify:
2. Have you exported every task? If not, STOP and FIX.
3. Have you generated any DEPRECATED code patterns? If yes, STOP and FIX.
## Consequences of incorrect implementations
## CONSEQUENCES OF INCORRECT IMPLEMENTATION
If you generate code that fails the verification steps above, your implementation will:
@@ -1265,10 +1265,10 @@ If you generate code that fails the verification steps above, your implementatio
2. Fail to deploy to the Trigger.dev servers
3. Fail to run in a local Dev environment
## AI model response template
## AI MODEL RESPONSE TEMPLATE
When asked about Trigger.dev task implementation, you MUST:
1. FIRST use code patterns from this guide
2. NEVER suggest deprecated approaches
3. VERIFY your response against the patterns shown here
4. If an answer cannot be found using this guide, look up further information ONLY from the official LLM-friendly version of the [Trigger.dev docs site](mdc:https:/trigger.dev/docs/llms.txt).
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/gh-cli
@@ -1 +0,0 @@
../../.agents/skills/vercel-react-best-practices
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/web-design-guidelines
+2 -3
View File
@@ -60,6 +60,5 @@ lib/emails/marketing
# trigger.dev
.trigger
# changelog and docs
changelog
.docs
# changelog
changelog
@@ -115,13 +115,11 @@ export default function EmailVerificationClient() {
<div className="flex w-full justify-center bg-gray-50 md:w-1/2 lg:w-1/2">
<div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
<div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
<Link href="https://www.papermark.com" target="_blank">
<img
src="/_static/papermark-logo.svg"
alt="Papermark Logo"
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
/>
</Link>
<img
src="/_static/papermark-logo.svg"
alt="Papermark Logo"
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
/>
<span className="text-balance text-3xl font-semibold text-gray-900">
Code Expired
</span>
@@ -153,13 +151,11 @@ export default function EmailVerificationClient() {
></div>
<div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
<div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
<Link href="https://www.papermark.com" target="_blank">
<img
src="/_static/papermark-logo.svg"
alt="Papermark Logo"
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
/>
</Link>
<img
src="/_static/papermark-logo.svg"
alt="Papermark Logo"
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
/>
<Link href="/">
<span className="text-balance text-3xl font-semibold text-gray-900">
Check your email
-77
View File
@@ -1,77 +0,0 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { signIn } from "next-auth/react";
/**
* SAML Callback Page
*
* This page handles IdP-initiated SSO flow:
* 1. User clicks the app tile in their IdP dashboard
* 2. Jackson processes the SAML response and redirects here with a `code`
* 3. We exchange the code via the `saml-idp` CredentialsProvider
*
* SP-initiated SSO (user clicks "Continue with SSO" on login page) is handled
* entirely by NextAuth's OAuth flow via the `saml` provider — it never hits this page.
*/
export default function SAMLCallbackClient() {
const searchParams = useSearchParams();
const router = useRouter();
const [status, setStatus] = useState<"loading" | "error">("loading");
const [errorMessage, setErrorMessage] = useState<string>("");
useEffect(() => {
const code = searchParams?.get("code");
if (code) {
signIn("saml-idp", {
code,
redirect: false,
}).then((result) => {
if (result?.ok) {
router.push("/dashboard");
} else {
setStatus("error");
setErrorMessage(
result?.error || "SSO authentication failed. Please try again.",
);
}
});
} else {
setStatus("error");
setErrorMessage(
"No authorization code received from your identity provider.",
);
}
}, [searchParams, router]);
if (status === "error") {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="mx-auto max-w-md text-center">
<h2 className="text-xl font-semibold text-gray-900">
SSO Login Failed
</h2>
<p className="mt-2 text-sm text-gray-600">{errorMessage}</p>
<button
onClick={() => router.push("/login")}
className="mt-4 rounded-md bg-gray-900 px-4 py-2 text-sm text-white hover:bg-gray-800"
>
Return to Login
</button>
</div>
</div>
);
}
return (
<div className="flex min-h-screen items-center justify-center">
<div className="mx-auto max-w-md text-center">
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900" />
<p className="text-sm text-gray-600">Completing SSO login...</p>
</div>
</div>
);
}
-12
View File
@@ -1,12 +0,0 @@
import { Metadata } from "next";
import SAMLCallbackClient from "./page-client";
export const metadata: Metadata = {
title: "SSO Login | Papermark",
description: "Completing SSO login",
};
export default function SAMLCallbackPage() {
return <SAMLCallbackClient />;
}
+6 -31
View File
@@ -1,13 +1,10 @@
"use client";
import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { AlertCircle } from "lucide-react";
import { SSOLogin } from "@/ee/features/security/sso";
import { signInWithPasskey } from "@teamhanko/passkeys-next-auth-provider/client";
import { signIn } from "next-auth/react";
import { toast } from "sonner";
@@ -27,9 +24,6 @@ import { Label } from "@/components/ui/label";
export default function Login() {
const { next } = useParams as { next?: string };
const router = useRouter();
const searchParams = useSearchParams();
const authError = searchParams?.get("error");
const isSSORequired = authError === "require-saml-sso";
const [lastUsed, setLastUsed] = useLastUsed();
const authMethods = ["google", "email", "linkedin", "passkey"] as const;
@@ -61,13 +55,11 @@ export default function Login() {
></div>
<div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
<div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
<Link href="https://www.papermark.com" target="_blank">
<img
src="/_static/papermark-logo.svg"
alt="Papermark Logo"
className="md:mb-48s -mt-8 mb-36 h-7 w-auto self-start sm:mb-32"
/>
</Link>
<img
src="/_static/papermark-logo.svg"
alt="Papermark Logo"
className="md:mb-48s -mt-8 mb-36 h-7 w-auto self-start sm:mb-32"
/>
<Link href="/">
<span className="text-balance text-3xl font-semibold text-gray-900">
Welcome to Papermark
@@ -77,20 +69,6 @@ export default function Login() {
Share documents. Not attachments.
</h3>
</div>
{isSSORequired && (
<div className="mx-4 mb-2 flex items-start gap-3 rounded-lg border border-orange-200 bg-orange-50 px-4 py-3 sm:mx-12">
<AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-orange-600" />
<div>
<p className="text-sm font-medium text-orange-900">
Your organization requires SSO login
</p>
<p className="mt-1 text-sm text-orange-700">
Please use the <strong>SAML SSO</strong> option below to sign
in with your company&apos;s identity provider.
</p>
</div>
</div>
)}
<form
className="flex flex-col gap-4 px-4 pt-8 sm:px-12"
onSubmit={(e) => {
@@ -231,9 +209,6 @@ export default function Login() {
{lastUsed === "passkey" && <LastUsed />}
</Button>
</div>
<div className="relative">
<SSOLogin autoExpand={isSSORequired} />
</div>
</div>
<p className="mt-10 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-12">
By clicking continue, you acknowledge that you have read and agree
+1 -1
View File
@@ -35,7 +35,7 @@ export default function Register() {
</div>
<div className="z-10 mx-5 mt-[calc(20vh)] h-fit w-full max-w-md overflow-hidden rounded-lg border border-border bg-gray-50 dark:bg-gray-900 sm:mx-0 sm:shadow-xl">
<div className="flex flex-col items-center justify-center space-y-3 px-4 py-6 pt-8 text-center sm:px-16">
<Link href="https://www.papermark.com" target="_blank">
<Link href="/">
<Image
src={PapermarkLogo}
width={119}
-77
View File
@@ -1,77 +0,0 @@
import { jackson } from "@/lib/jackson";
import type { OAuthReq } from "@boxyhq/saml-jackson";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(req: Request) {
try {
const { oauthController } = await jackson();
const url = new URL(req.url);
const requestParams = Object.fromEntries(
url.searchParams.entries(),
) as unknown as OAuthReq;
const { redirect_url, authorize_form } =
await oauthController.authorize(requestParams);
if (redirect_url) {
return NextResponse.redirect(redirect_url, { status: 302 });
} else if (authorize_form) {
return new Response(authorize_form, {
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return NextResponse.json(
{ error: "No redirect URL returned" },
{ status: 400 },
);
} catch (error: any) {
console.error("[SAML] Authorize error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
export async function POST(req: Request) {
try {
const { oauthController } = await jackson();
const contentType = req.headers.get("content-type") || "";
let body: Record<string, any>;
if (contentType.includes("application/x-www-form-urlencoded")) {
const formData = await req.formData();
body = Object.fromEntries(formData.entries());
} else {
body = await req.json();
}
const { redirect_url, authorize_form } =
await oauthController.authorize(body as unknown as OAuthReq);
if (redirect_url) {
return NextResponse.redirect(redirect_url, { status: 302 });
} else if (authorize_form) {
return new Response(authorize_form, {
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return NextResponse.json(
{ error: "No redirect URL returned" },
{ status: 400 },
);
} catch (error: any) {
console.error("[SAML] Authorize error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
-34
View File
@@ -1,34 +0,0 @@
import { jackson } from "@/lib/jackson";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
const { oauthController } = await jackson();
const formData = await req.formData();
const RelayState = (formData.get("RelayState") as string) || "";
const SAMLResponse = (formData.get("SAMLResponse") as string) || "";
const { redirect_url } = await oauthController.samlResponse({
RelayState,
SAMLResponse,
});
if (!redirect_url) {
return NextResponse.json(
{ error: "No redirect URL returned" },
{ status: 400 },
);
}
return NextResponse.redirect(redirect_url, { status: 302 });
} catch (error: any) {
console.error("[SAML] Callback error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
-33
View File
@@ -1,33 +0,0 @@
import { jackson } from "@/lib/jackson";
// These imports fix crypto module bundling issues with Jackson in Next.js.
// Without them, the serverless function bundle tree-shakes away jose's crypto
// primitives, causing ERR_CRYPTO_INVALID_KEYLEN at runtime.
// See: https://github.com/ory/polis/blob/main/pages/api/import-hack.ts
import * as jose from "jose";
import { NextResponse } from "next/server";
import * as openidClient from "openid-client";
// Reference the imports so they aren't removed by tree-shaking
const _dependencies = [jose, openidClient];
void _dependencies;
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
const { oauthController } = await jackson();
const formData = await req.formData();
const body = Object.fromEntries(formData.entries());
const token = await oauthController.token(body as any);
return NextResponse.json(token);
} catch (error: any) {
console.error("[SAML] Token error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
-35
View File
@@ -1,35 +0,0 @@
import { jackson } from "@/lib/jackson";
// Force-include crypto dependencies (same workaround as token route)
import * as jose from "jose";
import { NextResponse } from "next/server";
import * as openidClient from "openid-client";
const _dependencies = [jose, openidClient];
void _dependencies;
// Prevent Next.js from statically generating this route at build time —
// it requires a live database connection via Jackson.
export const dynamic = "force-dynamic";
export async function GET(req: Request) {
try {
const { oauthController } = await jackson();
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// RFC 6750: token type is case-insensitive
const token = authHeader.replace(/^bearer\s+/i, "");
const userInfo = await oauthController.userInfo(token);
return NextResponse.json(userInfo);
} catch (error: any) {
console.error("[SAML] UserInfo error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
-66
View File
@@ -1,66 +0,0 @@
import { jackson, jacksonProduct } from "@/lib/jackson";
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
/**
* POST /api/auth/saml/verify
* Verifies that a team has SSO configured.
* Accepts either `slug` (preferred, user-friendly) or `teamId` (fallback).
* Returns only the teamId — no team names, provider info, or other metadata.
*/
export async function POST(req: Request) {
try {
const body = await req.json();
const { slug, teamId } = body;
if (!slug && !teamId) {
return NextResponse.json(
{ error: "Team slug or ID is required" },
{ status: 400 },
);
}
// Look up team by slug first, then by ID
const team = slug
? await prisma.team.findUnique({
where: { slug },
select: { id: true, ssoEnabled: true },
})
: await prisma.team.findUnique({
where: { id: teamId },
select: { id: true, ssoEnabled: true },
});
const ssoUnavailable = NextResponse.json(
{ error: "SSO is not available for this team." },
{ status: 404 },
);
if (!team || !team.ssoEnabled) {
return ssoUnavailable;
}
// Check Jackson for actual SAML connections
const { apiController } = await jackson();
const connections = await apiController.getConnections({
tenant: team.id,
product: jacksonProduct,
});
if (!connections || connections.length === 0) {
return ssoUnavailable;
}
// Only return the team ID — no names, providers, or other metadata
return NextResponse.json({ data: { teamId: team.id } });
} catch (error: any) {
console.error("[SAML] Verify error:", error);
return NextResponse.json(
{ error: "Something went wrong" },
{ status: 500 },
);
}
}
-55
View File
@@ -4,10 +4,7 @@ import { processDocument } from "@/lib/api/documents/process-document";
import { verifyDataroomSession } from "@/lib/auth/dataroom-auth";
import { DocumentData } from "@/lib/documents/create-document";
import prisma from "@/lib/prisma";
import { sendDataroomUploadNotificationTask } from "@/lib/trigger/dataroom-upload-notification";
import { supportsAdvancedExcelMode } from "@/lib/utils/get-content-type";
import { runs } from "@trigger.dev/sdk/v3";
import { waitUntil } from "@vercel/functions";
export async function POST(
request: NextRequest,
@@ -48,9 +45,7 @@ export async function POST(
where: { id: linkId, dataroomId },
select: {
id: true,
name: true,
enableUpload: true,
enableNotification: true,
uploadFolderId: true,
dataroomId: true,
teamId: true,
@@ -153,56 +148,6 @@ export async function POST(
},
});
// 4. Send upload notification to team if enabled
if (link.enableNotification) {
try {
// Cancel any existing pending notification runs for this viewer+dataroom+link
// Note: runs.list tag filter uses OR logic, so we must post-filter
// to ensure we only cancel runs matching ALL three tags
const requiredTags = [
`dataroom_${dataroomId}`,
`link_${linkId}`,
`viewer_${viewerId}`,
];
const allRuns = await runs.list({
taskIdentifier: ["send-dataroom-upload-notification"],
tag: requiredTags,
status: ["DELAYED", "QUEUED"],
period: "10m",
});
const matchingRuns = allRuns.data.filter((run) =>
requiredTags.every((tag) => run.tags?.includes(tag)),
);
await Promise.all(matchingRuns.map((run) => runs.cancel(run.id)));
// Trigger a new notification with 5-minute delay to batch uploads
waitUntil(
sendDataroomUploadNotificationTask.trigger(
{
dataroomId,
linkId,
viewerId,
teamId: link.teamId,
},
{
idempotencyKey: `upload-notification-${link.teamId}-${dataroomId}-${linkId}-${viewerId}-${newDataroomDocument.id}`,
tags: [
`team_${link.teamId}`,
`dataroom_${dataroomId}`,
`link_${linkId}`,
`viewer_${viewerId}`,
],
delay: new Date(Date.now() + 5 * 60 * 1000), // 5 minute delay
},
),
);
} catch (error) {
console.error("Error triggering upload notification:", error);
}
}
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error uploading document:", error);
@@ -1,315 +0,0 @@
import { jackson } from "@/lib/jackson";
import prisma from "@/lib/prisma";
import type { DirectorySyncEvent } from "@boxyhq/saml-jackson";
import { createHash } from "crypto";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
/** Return a truncated SHA-256 hex digest (first 12 chars) for log-safe pseudonymisation. */
function hashEmail(email: string): string {
return createHash("sha256").update(email).digest("hex").slice(0, 12);
}
const handler = async (
req: Request,
{ params }: { params: Promise<{ directory: string[] }> },
) => {
try {
const resolvedParams = await params;
const headersList = await headers();
const authHeader = headersList.get("Authorization");
const apiSecret = authHeader ? authHeader.split(" ")[1] : null;
const url = new URL(req.url);
const query = Object.fromEntries(url.searchParams.entries());
const [directoryId, path, resourceId] = resolvedParams.directory;
let body: any = {};
try {
body = await req.json();
} catch {
body = {};
}
const { directorySyncController } = await jackson();
const request = {
method: req.method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
body,
directoryId,
resourceId,
resourceType: (path === "Users" ? "users" : "groups") as
| "users"
| "groups",
apiSecret,
query: {
count: query.count ? parseInt(query.count) : undefined,
startIndex: query.startIndex ? parseInt(query.startIndex) : undefined,
filter: query.filter as string,
},
};
const { status, data } = await directorySyncController.requests.handle(
request,
handleSCIMEvents,
);
return NextResponse.json(data, { status });
} catch (error: any) {
console.error("[SCIM] Request error:", error);
return NextResponse.json(
{
schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
detail: "Internal server error",
status: 500,
},
{ status: 500 },
);
}
};
export {
handler as DELETE,
handler as GET,
handler as PATCH,
handler as POST,
handler as PUT,
};
// ──────────────────────────────────────────────────────────
// SCIM Event Handler — sync changes to the main app DB
// ──────────────────────────────────────────────────────────
async function handleSCIMEvents(event: DirectorySyncEvent) {
const { event: eventType, data, tenant } = event;
// Verify the team exists and has SSO enabled
const team = await prisma.team.findUnique({
where: { id: tenant },
select: { id: true, plan: true, ssoEnabled: true },
});
if (!team || !team.ssoEnabled) {
console.warn(
`[SCIM] Ignoring event for tenant ${tenant} — SSO not enabled`,
);
return;
}
// Plan gate: only datarooms-premium or higher
const allowedPlans = ["datarooms-premium", "datarooms-premium+old"];
if (!allowedPlans.includes(team.plan)) {
console.warn(
`[SCIM] Ignoring event for tenant ${tenant} — plan ${team.plan} not eligible`,
);
return;
}
if (!("email" in data) || !data.email) {
return;
}
// Normalize once so look-ups/upserts always use a consistent lowercase key
const email = data.email.trim().toLowerCase();
try {
switch (eventType) {
case "user.created": {
console.log(
`[SCIM] User created: user_${hashEmail(email)} for tenant ${tenant}`,
);
const user = await prisma.user.upsert({
where: { email },
create: {
email,
name: [data.first_name, data.last_name].filter(Boolean).join(" "),
},
update: {},
});
await prisma.userTeam.upsert({
where: {
userId_teamId: {
userId: user.id,
teamId: tenant,
},
},
update: {},
create: {
userId: user.id,
teamId: tenant,
role: "MEMBER",
},
});
break;
}
case "user.updated": {
console.log(
`[SCIM] User updated: user_${hashEmail(email)} for tenant ${tenant}`,
);
// Handle Azure AD's active/inactive (can be boolean or string in any casing)
const rawActive = (data as any).active;
const normalizedActive =
rawActive === undefined
? undefined
: typeof rawActive === "string"
? rawActive.toLowerCase() === "true"
: Boolean(rawActive);
const isActive = normalizedActive === true;
const isInactive = normalizedActive === false;
if (isInactive) {
// Deactivated — remove from team (same as user.deleted)
const user = await prisma.user.findUnique({
where: { email },
});
if (user) {
await Promise.all([
prisma.link
.updateMany({
where: {
teamId: tenant,
ownerId: user.id,
},
data: {
ownerId: null,
},
})
.catch(() => {
console.warn(
`[SCIM] Could not reset link ownership for user_${hashEmail(email)}`,
);
}),
prisma.userTeam
.delete({
where: {
userId_teamId: {
userId: user.id,
teamId: tenant,
},
},
})
.catch(() => {
console.warn(
`[SCIM] Could not remove team membership for user_${hashEmail(email)}`,
);
}),
]);
}
} else if (isActive) {
// Reactivated — re-add to team
const user = await prisma.user.upsert({
where: { email },
create: {
email,
name: [data.first_name, data.last_name]
.filter(Boolean)
.join(" "),
},
update: {
name:
[data.first_name, data.last_name].filter(Boolean).join(" ") ||
undefined,
},
});
await prisma.userTeam.upsert({
where: {
userId_teamId: {
userId: user.id,
teamId: tenant,
},
},
update: {},
create: {
userId: user.id,
teamId: tenant,
role: "MEMBER",
},
});
} else {
// Just a name/attribute update
await prisma.user
.update({
where: { email },
data: {
name:
[data.first_name, data.last_name]
.filter(Boolean)
.join(" ") || undefined,
},
})
.catch(() => {
console.warn(
`[SCIM] Could not update user user_${hashEmail(email)} — user not found`,
);
});
}
break;
}
case "user.deleted": {
console.log(
`[SCIM] User deleted: user_${hashEmail(email)} for tenant ${tenant}`,
);
const deletedUser = await prisma.user.findUnique({
where: { email },
});
if (deletedUser) {
await Promise.all([
prisma.link
.updateMany({
where: {
teamId: tenant,
ownerId: deletedUser.id,
},
data: {
ownerId: null,
},
})
.catch(() => {
console.warn(
`[SCIM] Could not reset link ownership for user_${hashEmail(email)}`,
);
}),
prisma.userTeam
.delete({
where: {
userId_teamId: {
userId: deletedUser.id,
teamId: tenant,
},
},
})
.catch(() => {
console.warn(
`[SCIM] Could not remove team membership for user_${hashEmail(email)}`,
);
}),
]);
}
break;
}
case "group.created":
case "group.updated":
case "group.deleted":
case "group.user_added":
case "group.user_removed": {
console.log(`[SCIM] Group event ${eventType} for tenant ${tenant}`);
break;
}
}
} catch (error) {
console.error(`[SCIM] Error handling event ${eventType}:`, error);
}
}
@@ -1,186 +0,0 @@
import { jackson, jacksonProduct } from "@/lib/jackson";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
function isJacksonUnavailableError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return (
message.includes("error connecting to engine") ||
message.includes("Missing Jackson DB URL") ||
message.includes("ENOENT: no such file or directory, open 'system'")
);
}
async function getAuthenticatedAdmin(teamId: string) {
const session = await getServerSession(authOptions);
if (!session) return null;
const userId = (session.user as CustomUser).id;
const teamAccess = await prisma.userTeam.findUnique({
where: { userId_teamId: { userId, teamId } },
select: { role: true },
});
if (!teamAccess || teamAccess.role !== "ADMIN") return null;
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { id: true, plan: true, ssoEnabled: true },
});
if (!team) return null;
return { userId, team };
}
// GET /api/teams/:teamId/directory-sync — list SCIM directories
export async function GET(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
if (!auth.team.ssoEnabled || !SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
return NextResponse.json({ directories: [] });
}
const { directorySyncController } = await jackson();
const { data, error } =
await directorySyncController.directories.getByTenantAndProduct(
teamId,
jacksonProduct,
);
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
return NextResponse.json({ directories: data });
} catch (error: any) {
if (isJacksonUnavailableError(error)) {
console.warn("[SCIM] Jackson unavailable, returning empty directories", error);
return NextResponse.json({ directories: [] });
}
console.error("[SCIM] Get directories error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
// POST /api/teams/:teamId/directory-sync — create a SCIM directory connection
export async function POST(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Plan gate
if (!SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
return NextResponse.json(
{ error: "SCIM Directory Sync requires a Datarooms Premium plan" },
{ status: 403 },
);
}
// Feature flag gate
if (!auth.team.ssoEnabled) {
return NextResponse.json(
{ error: "SSO is not enabled for this team" },
{ status: 403 },
);
}
try {
const { directorySyncController } = await jackson();
const body = await req.json();
const { name, type, currentDirectoryId } = body;
// Create the new directory first; only delete the old one on success
const result = await directorySyncController.directories.create({
tenant: teamId,
product: jacksonProduct,
name: name || "Papermark SCIM Directory",
type: type || "azure-scim-v2",
});
if (result.error) {
return NextResponse.json(
{ error: result.error.message },
{ status: 400 },
);
}
// If replacing an existing directory, delete the old one after successful create
if (currentDirectoryId) {
await directorySyncController.directories.delete(currentDirectoryId);
}
return NextResponse.json(result, { status: 201 });
} catch (error: any) {
console.error("[SCIM] Create directory error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
// DELETE /api/teams/:teamId/directory-sync — delete a SCIM directory
export async function DELETE(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const { directorySyncController } = await jackson();
const body = await req.json();
const { directoryId } = body;
if (!directoryId) {
return NextResponse.json(
{ error: "directoryId is required" },
{ status: 400 },
);
}
const { error } =
await directorySyncController.directories.delete(directoryId);
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
return NextResponse.json({ ok: true });
} catch (error: any) {
console.error("[SCIM] Delete directory error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
-408
View File
@@ -1,408 +0,0 @@
import { jackson, jacksonProduct, samlAudience } from "@/lib/jackson";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
import { isGenericDomain } from "@/lib/utils/email-domain";
import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
function isJacksonUnavailableError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return (
message.includes("error connecting to engine") ||
message.includes("Missing Jackson DB URL") ||
message.includes("ENOENT: no such file or directory, open 'system'")
);
}
async function getAuthenticatedAdmin(teamId: string) {
const session = await getServerSession(authOptions);
if (!session) return null;
const userId = (session.user as CustomUser).id;
const teamAccess = await prisma.userTeam.findUnique({
where: { userId_teamId: { userId, teamId } },
select: { role: true },
});
if (!teamAccess || teamAccess.role !== "ADMIN") return null;
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { id: true, plan: true, ssoEnabled: true, ssoEmailDomain: true, ssoEnforcedAt: true, slug: true },
});
if (!team) return null;
return { userId, team, email: (session.user as CustomUser).email! };
}
// GET /api/teams/:teamId/saml — list SAML connections + issuer/acs info
export async function GET(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
if (!auth.team.ssoEnabled || !SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
return NextResponse.json({
connections: [],
issuer: samlAudience,
acs: `${process.env.NEXTAUTH_URL}/api/auth/saml/callback`,
ssoEmailDomain: auth.team.ssoEmailDomain,
ssoEnforcedAt: auth.team.ssoEnforcedAt,
slug: auth.team.slug,
});
}
const { apiController } = await jackson();
const connections = await apiController.getConnections({
tenant: teamId,
product: jacksonProduct,
});
return NextResponse.json({
connections,
issuer: samlAudience,
acs: `${process.env.NEXTAUTH_URL}/api/auth/saml/callback`,
ssoEmailDomain: auth.team.ssoEmailDomain,
ssoEnforcedAt: auth.team.ssoEnforcedAt,
slug: auth.team.slug,
});
} catch (error: any) {
if (isJacksonUnavailableError(error)) {
console.warn("[SAML] Jackson unavailable, returning empty connections", error);
return NextResponse.json({
connections: [],
issuer: samlAudience,
acs: `${process.env.NEXTAUTH_URL}/api/auth/saml/callback`,
ssoEmailDomain: auth.team.ssoEmailDomain,
ssoEnforcedAt: auth.team.ssoEnforcedAt,
slug: auth.team.slug,
});
}
console.error("[SAML] Get connections error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
// POST /api/teams/:teamId/saml — create a new SAML connection
export async function POST(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Plan gate
if (!SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
return NextResponse.json(
{ error: "SSO requires a Datarooms Premium plan" },
{ status: 403 },
);
}
// Feature flag gate
if (!auth.team.ssoEnabled) {
return NextResponse.json(
{ error: "SSO is not enabled for this team" },
{ status: 403 },
);
}
try {
const { apiController } = await jackson();
const body = await req.json();
const { rawMetadata, encodedRawMetadata, metadataUrl, domain } = body;
if (!rawMetadata && !metadataUrl && !encodedRawMetadata) {
return NextResponse.json(
{
error:
"Either rawMetadata, encodedRawMetadata, or metadataUrl is required",
},
{ status: 400 },
);
}
// Normalize the explicit domain provided by the admin (if any)
const explicitDomain = typeof domain === "string"
? domain.trim().toLowerCase().replace(/^@/, "")
: undefined;
// Validate explicit domain format if provided
if (explicitDomain && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(explicitDomain)) {
return NextResponse.json(
{ error: "Invalid domain format. Please provide a valid domain (e.g., example.com)." },
{ status: 400 },
);
}
// Reject public / free email provider domains SSO should only be
// configured for organisation-owned domains.
if (explicitDomain && isGenericDomain(explicitDomain)) {
return NextResponse.json(
{
error:
"Public email domains (e.g., gmail.com, outlook.com) cannot be used for SSO. Please provide your organization's domain.",
},
{ status: 400 },
);
}
const connection = await apiController.createSAMLConnection({
defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,
redirectUrl: process.env.NEXTAUTH_URL as string,
tenant: teamId,
product: jacksonProduct,
rawMetadata: rawMetadata || undefined,
encodedRawMetadata: encodedRawMetadata || undefined,
metadataUrl: metadataUrl || undefined,
});
// Attempt to extract a domain hint from the IdP metadata returned by the
// SAML connection. Standard IdP entity IDs / SSO URLs sometimes contain
// the organisation's own domain (e.g. for self-hosted IdPs). We use this
// as an additional validation signal if the admin supplied a domain we
// check it is consistent; if not, we fall back to the metadata hint only
// when it looks like a real organisation domain (not a generic IdP host).
let metadataDomain: string | undefined;
try {
const idpMeta = (connection as any)?.idpMetadata;
const candidateUrls: string[] = [
idpMeta?.entityID,
idpMeta?.sso?.postUrl,
idpMeta?.sso?.redirectUrl,
].filter(Boolean);
const genericIdpHosts = new Set([
"accounts.google.com",
"login.microsoftonline.com",
"sts.windows.net",
"idp.ssocircle.com",
"www.okta.com",
"dev.okta.com",
"auth0.com",
"onelogin.com",
"pingone.com",
]);
for (const raw of candidateUrls) {
try {
const host = new URL(raw).hostname.toLowerCase();
// Skip well-known generic IdP hosts and public email domains
if (
[...genericIdpHosts].some((g) => host === g || host.endsWith(`.${g}`)) ||
isGenericDomain(host)
) {
continue;
}
// Must have at least two labels (e.g. "company.com")
if (host.split(".").length >= 2) {
metadataDomain = host;
break;
}
} catch {
// not a valid URL skip
}
}
} catch {
// metadata extraction is best-effort
}
// Determine the validated domain to persist:
// 1. Prefer the explicitly admin-provided domain.
// 2. Fall back to a domain extracted from metadata (if non-generic).
// 3. If neither is available, do NOT store a domain.
const validatedDomain = explicitDomain || metadataDomain || undefined;
// Only persist ssoEmailDomain when we have a validated value
if (validatedDomain) {
await prisma.team.update({
where: { id: teamId },
data: {
ssoEmailDomain: validatedDomain,
},
});
}
return NextResponse.json(connection, { status: 201 });
} catch (error: any) {
console.error("[SAML] Create connection error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
// PATCH /api/teams/:teamId/saml — update SSO enforcement settings
export async function PATCH(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const body = await req.json();
const { enforced } = body;
if (typeof enforced !== "boolean") {
return NextResponse.json(
{ error: "'enforced' must be a boolean" },
{ status: 400 },
);
}
// Can only enforce if there's an ssoEmailDomain set (which is set when SAML is configured)
if (enforced && !auth.team.ssoEmailDomain) {
return NextResponse.json(
{
error:
"Cannot enforce SSO without a configured email domain. Please configure SAML first.",
},
{ status: 400 },
);
}
// Verify there are active SAML connections before enforcing
if (enforced) {
const { apiController } = await jackson();
const connections = await apiController.getConnections({
tenant: teamId,
product: jacksonProduct,
});
if (!connections || connections.length === 0) {
return NextResponse.json(
{
error:
"Cannot enforce SSO without an active SAML connection. Please configure SAML first.",
},
{ status: 400 },
);
}
}
const now = enforced ? new Date() : null;
await prisma.team.update({
where: { id: teamId },
data: {
ssoEnforcedAt: now,
},
});
return NextResponse.json({
enforced,
ssoEnforcedAt: now?.toISOString() ?? null,
});
} catch (error: any) {
console.error("[SAML] Update enforcement error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
// DELETE /api/teams/:teamId/saml — remove a SAML connection
export async function DELETE(
req: Request,
{ params }: { params: Promise<{ teamId: string }> },
) {
const { teamId } = await params;
const auth = await getAuthenticatedAdmin(teamId);
if (!auth) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const { apiController } = await jackson();
const body = await req.json();
const { clientID, clientSecret } = body;
if (!clientID || !clientSecret) {
return NextResponse.json(
{ error: "clientID and clientSecret are required" },
{ status: 400 },
);
}
// Ownership check: verify the connection belongs to this team before deleting
const existingConnections = await apiController.getConnections({
clientID,
});
const connection = Array.isArray(existingConnections)
? existingConnections[0]
: existingConnections;
if (!connection) {
return NextResponse.json(
{ error: "SAML connection not found" },
{ status: 404 },
);
}
if (connection.tenant !== teamId) {
return NextResponse.json(
{ error: "You do not have permission to delete this connection" },
{ status: 403 },
);
}
await apiController.deleteConnections({
clientID,
clientSecret,
tenant: teamId,
product: jacksonProduct,
});
// Check if there are remaining connections
const remaining = await apiController.getConnections({
tenant: teamId,
product: jacksonProduct,
});
if (!remaining || (Array.isArray(remaining) && remaining.length === 0)) {
// No more connections — clear SSO domain and enforcement
await prisma.team.update({
where: { id: teamId },
data: {
ssoEmailDomain: null,
ssoEnforcedAt: null,
},
});
}
return NextResponse.json({ ok: true });
} catch (error: any) {
console.error("[SAML] Delete connection error:", error);
return NextResponse.json(
{ error: error.message || "Internal server error" },
{ status: 500 },
);
}
}
+1 -16
View File
@@ -5,7 +5,6 @@ import {
formatZodError,
} from "@/ee/features/workflows/lib/validation";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { customAlphabet } from "nanoid";
import { getServerSession } from "next-auth";
import { z } from "zod";
@@ -283,11 +282,6 @@ export async function DELETE(
select: {
id: true,
entryLinkId: true,
entryLink: {
select: {
slug: true,
},
},
},
});
@@ -298,12 +292,6 @@ export async function DELETE(
);
}
// Generate a random suffix for the deleted slug to free up the original slug
const generateDeletedSuffix = customAlphabet(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
6,
);
// Delete workflow and entry link in transaction
// Note: Steps and executions will cascade delete via Prisma relations
await prisma.$transaction([
@@ -311,15 +299,12 @@ export async function DELETE(
prisma.workflow.delete({
where: { id: workflowId },
}),
// Soft delete entry link and rename slug so it can be reused
// Delete entry link
prisma.link.update({
where: { id: workflow.entryLinkId },
data: {
deletedAt: new Date(),
isArchived: true,
...(workflow.entryLink?.slug && {
slug: `${workflow.entryLink.slug}-DELETED-${generateDeletedSuffix()}`,
}),
},
}),
]);
-1
View File
@@ -230,7 +230,6 @@ export async function POST(req: NextRequest) {
data: {
linkType: "WORKFLOW_LINK",
teamId,
ownerId: userId,
name: `${name} - Entry Link`,
slug: slug || null,
domainId: domainId,
+21 -12
View File
@@ -46,6 +46,7 @@ export async function POST(request: NextRequest) {
documentName,
hasPages,
ownerId,
dataroomVerified,
linkType,
dataroomViewId,
viewType,
@@ -60,6 +61,7 @@ export async function POST(request: NextRequest) {
documentName: string | undefined;
hasPages: boolean | undefined;
ownerId: string | null;
dataroomVerified: boolean | undefined;
linkType: string;
dataroomViewId?: string;
viewType: "DATAROOM_VIEW" | "DOCUMENT_VIEW";
@@ -214,6 +216,7 @@ export async function POST(request: NextRequest) {
linkId,
);
console.log("previewSession", previewSession);
if (!previewSession) {
return NextResponse.json(
{
@@ -234,7 +237,6 @@ export async function POST(request: NextRequest) {
link.dataroomId!,
);
// If we have a dataroom session, use its verified status
if (dataroomSession) {
isEmailVerified = dataroomSession.verified;
@@ -395,7 +397,7 @@ export async function POST(request: NextRequest) {
// Request OTP Code for email verification if
// 1) email verification is required and
// 2) code is not provided or token not provided
if (link.emailAuthenticated && !code && !token) {
if (link.emailAuthenticated && !code && !token && !dataroomVerified) {
const ipAddressValue = ipAddress(request);
// Rate limit per email/link combination (1 per 30 seconds) to prevent OTP flooding
@@ -451,7 +453,7 @@ export async function POST(request: NextRequest) {
);
}
if (link.emailAuthenticated && code) {
if (link.emailAuthenticated && code && !dataroomVerified) {
const ipAddressValue = ipAddress(request);
const { success } = await ratelimit(10, "1 m").limit(
`verify-otp:${ipAddressValue}`,
@@ -520,7 +522,7 @@ export async function POST(request: NextRequest) {
isEmailVerified = true;
}
if (link.emailAuthenticated && token) {
if (link.emailAuthenticated && token && !dataroomVerified) {
const ipAddressValue = ipAddress(request);
const { success } = await ratelimit(10, "1 m").limit(
`verify-email:${ipAddressValue}`,
@@ -570,6 +572,9 @@ export async function POST(request: NextRequest) {
isEmailVerified = true;
}
if (link.emailAuthenticated && dataroomVerified) {
isEmailVerified = true;
}
}
let viewer: { id: string; email: string; verified: boolean } | null = null;
@@ -664,6 +669,7 @@ export async function POST(request: NextRequest) {
// ** DATAROOM_VIEW **
if (viewType === "DATAROOM_VIEW") {
console.log("viewType is DATAROOM_VIEW");
try {
let newDataroomView: { id: string } | null = null;
if (!isPreview) {
@@ -686,7 +692,7 @@ export async function POST(request: NextRequest) {
clickId: newId("linkView"),
viewId: newDataroomView.id,
linkId,
dataroomId: link.dataroomId!,
dataroomId,
teamId: link.teamId!,
enableNotification: link.enableNotification,
isPaused,
@@ -699,7 +705,7 @@ export async function POST(request: NextRequest) {
try {
await notifyDataroomAccess({
teamId: link.teamId!,
dataroomId: link.dataroomId!,
dataroomId,
linkId,
viewerEmail: verifiedEmail ?? email,
viewerId: viewer?.id,
@@ -737,7 +743,7 @@ export async function POST(request: NextRequest) {
// Create a dataroom session token if a dataroom session doesn't exist yet
if (!dataroomSession && !isPreview) {
const newDataroomSession = await createDataroomSession(
link.dataroomId!,
dataroomId,
linkId,
newDataroomView?.id!,
ipAddress(request) ?? LOCALHOST_IP,
@@ -790,6 +796,9 @@ export async function POST(request: NextRequest) {
// if dataroomSession is not present, create a dataroom view first
if (!dataroomSession) {
console.log(
"no dataroom session present, creating new dataroom view",
);
dataroomView = await prisma.view.create({
data: { ...viewFields, viewType: "DATAROOM_VIEW" },
select: { id: true },
@@ -802,7 +811,7 @@ export async function POST(request: NextRequest) {
clickId: newId("linkView"),
viewId: dataroomView.id,
linkId,
dataroomId: link.dataroomId!,
dataroomId,
teamId: link.teamId!,
enableNotification: link.enableNotification,
isPaused,
@@ -830,7 +839,7 @@ export async function POST(request: NextRequest) {
await notifyDocumentView({
teamId: link.teamId!,
documentId,
dataroomId: link.dataroomId!,
dataroomId,
linkId,
viewerEmail: verifiedEmail ?? email,
viewerId: viewer?.id,
@@ -946,12 +955,12 @@ export async function POST(request: NextRequest) {
link.permissionGroupId) &&
effectiveGroupId &&
documentId &&
link.dataroomId
dataroomId
) {
const dataroomDocument = await prisma.dataroomDocument.findUnique({
where: {
dataroomId_documentId: {
dataroomId: link.dataroomId,
dataroomId: dataroomId,
documentId: documentId,
},
},
@@ -1051,7 +1060,7 @@ export async function POST(request: NextRequest) {
// Create a dataroom session token if a dataroom session doesn't exist yet
if (!dataroomSession && !isPreview) {
const newDataroomSession = await createDataroomSession(
link.dataroomId!,
dataroomId,
linkId,
dataroomView?.id!,
ipAddress(request) ?? LOCALHOST_IP,
+12 -1
View File
@@ -106,8 +106,19 @@ export function UpgradePlanModal({
trigger: trigger,
teamId: teamInfo?.currentTeam?.id,
});
// Track upgrade click for email scheduling (with trigger info for personalization)
if (teamInfo?.currentTeam?.id) {
fetch(`/api/teams/${teamInfo.currentTeam.id}/billing/track-upgrade-click`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ trigger }),
}).catch(() => {
// Silently fail - this is just for tracking
});
}
}
}, [open, trigger]);
}, [open, trigger, teamInfo?.currentTeam?.id]);
// Track analytics event when child button is present
const handleUpgradeClick = () => {
@@ -217,10 +217,21 @@ export function UpgradePlanModalWithDiscount({
trigger: trigger,
teamId,
});
// Track upgrade click for email scheduling (with trigger info for personalization)
if (teamId) {
fetch(`/api/teams/${teamId}/billing/track-upgrade-click`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ trigger }),
}).catch(() => {
// Silently fail - this is just for tracking
});
}
} else {
setDataRoomsPlanSelection("base");
}
}, [open, trigger]);
}, [open, trigger, teamId]);
const handleUpgradeClick = () => {
analytics.capture("Upgrade Button Clicked", {
+12 -1
View File
@@ -193,10 +193,21 @@ export function UpgradePlanModal({
trigger: trigger,
teamId,
});
// Track upgrade click for email scheduling (with trigger info for personalization)
if (teamId) {
fetch(`/api/teams/${teamId}/billing/track-upgrade-click`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ trigger }),
}).catch(() => {
// Silently fail - this is just for tracking
});
}
} else {
setDataRoomsPlanSelection("base");
}
}, [open, trigger]);
}, [open, trigger, teamId]);
const handleUpgradeClick = () => {
analytics.capture("Upgrade Button Clicked", {
@@ -1,49 +1,68 @@
import { useState } from "react";
import { DownloadIcon } from "lucide-react";
import { toast } from "sonner";
import { DownloadProgressModal } from "@/components/datarooms/download-progress-modal";
import { ResponsiveButton } from "@/components/ui/responsive-button";
export default function DownloadDataroomButton({
teamId,
dataroomId,
dataroomName,
}: {
teamId: string;
dataroomId: string;
dataroomName?: string;
}) {
const [showDownloadModal, setShowDownloadModal] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const openDownloadModal = () => {
// Open the modal - it will show existing downloads and allow starting new ones
setShowDownloadModal(true);
const downloadDataroom = async () => {
setIsLoading(true);
try {
toast.promise(
fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/download/bulk`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
}),
{
loading: "Downloading dataroom...",
success: async (response) => {
const { downloadUrl } = await response.json();
const link = document.createElement("a");
link.href = downloadUrl;
link.rel = "noopener noreferrer";
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
}, 100);
return "Dataroom downloaded successfully.";
},
error: (error) => {
console.log(error);
return (
error.message || "An error occurred while downloading dataroom."
);
},
},
);
} catch (error) {
console.error(error);
} finally {
setIsLoading(false);
}
};
const handleCloseDownloadModal = () => {
setShowDownloadModal(false);
};
return (
<>
<ResponsiveButton
icon={<DownloadIcon className="h-4 w-4" />}
text="Download"
onClick={openDownloadModal}
variant="outline"
size="sm"
/>
{/* Download Progress Modal */}
<DownloadProgressModal
isOpen={showDownloadModal}
onClose={handleCloseDownloadModal}
jobId={null}
dataroomName={dataroomName}
teamId={teamId}
dataroomId={dataroomId}
/>
</>
<ResponsiveButton
icon={<DownloadIcon className="h-4 w-4" />}
text="Download"
onClick={downloadDataroom}
variant="outline"
size="sm"
loading={isLoading}
/>
);
}
@@ -8,7 +8,6 @@ import { TeamContextType } from "@/context/team-context";
import {
ArchiveXIcon,
BetweenHorizontalStartIcon,
FilePenIcon,
FileSlidersIcon,
FolderInputIcon,
MoreVertical,
@@ -40,7 +39,6 @@ import {
import { AddToDataroomModal } from "../documents/add-document-to-dataroom-modal";
import { DocumentPreviewButton } from "../documents/document-preview-button";
import FileProcessStatusBar from "../documents/file-process-status-bar";
import { EditDataroomDocumentModal } from "./edit-dataroom-document-modal";
import { SetUnifiedPermissionsModal } from "./groups/set-unified-permissions-modal";
import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";
@@ -76,7 +74,6 @@ export default function DataroomDocumentCard({
const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
const [menuOpen, setMenuOpen] = useState<boolean>(false);
const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);
const [renameOpen, setRenameOpen] = useState<boolean>(false);
const dropdownRef = useRef<HTMLDivElement | null>(null);
const [addDataRoomOpen, setAddDataRoomOpen] = useState<boolean>(false);
@@ -95,14 +92,6 @@ export default function DataroomDocumentCard({
}
}, [moveFolderOpen]);
useEffect(() => {
if (!renameOpen) {
setTimeout(() => {
document.body.style.pointerEvents = "";
});
}
}, [renameOpen]);
useEffect(() => {
function handleClickOutside(event: { target: any }) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
@@ -298,15 +287,6 @@ export default function DataroomDocumentCard({
</DropdownMenuTrigger>
<DropdownMenuContent align="end" ref={dropdownRef}>
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
setRenameOpen(true);
}}
>
<FilePenIcon className="mr-2 h-4 w-4" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
@@ -373,15 +353,6 @@ export default function DataroomDocumentCard({
/>
)}
</div>
{renameOpen ? (
<EditDataroomDocumentModal
open={renameOpen}
setOpen={setRenameOpen}
documentId={dataroomDocument.document.id}
documentName={dataroomDocument.document.name}
dataroomId={dataroomId}
/>
) : null}
{addDataRoomOpen ? (
<AddToDataroomModal
open={addDataRoomOpen}
@@ -1,681 +0,0 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import {
AlertCircle,
CheckCircle2,
ChevronDown,
ChevronUp,
Download,
FileArchive,
Loader2,
Plus,
XCircle,
} from "lucide-react";
import { DownloadJob } from "@/lib/redis-download-job-store";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
export interface DownloadJobStatus {
id: string;
status: "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
progress: number;
totalFiles: number;
processedFiles: number;
downloadUrls?: string[];
error?: string;
isReady: boolean;
dataroomName: string;
createdAt: string;
completedAt?: string;
expiresAt?: string;
}
interface DownloadProgressModalProps {
isOpen: boolean;
onClose: () => void;
jobId: string | null;
dataroomName?: string;
// For team member downloads (uses next-auth session)
teamId: string;
dataroomId: string;
}
export function DownloadProgressModal({
isOpen,
onClose,
jobId,
dataroomName,
teamId,
dataroomId,
}: DownloadProgressModalProps) {
const [status, setStatus] = useState<DownloadJobStatus | null>(null);
const [error, setError] = useState<string | null>(null);
const [isPolling, setIsPolling] = useState(false);
const [existingDownloads, setExistingDownloads] = useState<DownloadJob[]>([]);
const [loading, setLoading] = useState(true);
const [showNewDownload, setShowNewDownload] = useState(false);
const [isStartingDownload, setIsStartingDownload] = useState(false);
const [expandedDownloadId, setExpandedDownloadId] = useState<string | null>(
null,
);
const [downloadProgress, setDownloadProgress] = useState<{
downloadId: string;
current: number;
total: number;
} | null>(null);
const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
// Cleanup interval on component unmount
useEffect(() => {
return () => {
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
}
};
}, []);
// Fetch existing downloads when modal opens
useEffect(() => {
if (!isOpen || !teamId || !dataroomId) return;
const fetchExistingDownloads = async () => {
try {
setLoading(true);
const endpoint = `/api/teams/${teamId}/datarooms/${dataroomId}/download/jobs`;
const response = await fetch(endpoint, {
method: "GET",
credentials: "include",
});
if (response.ok) {
const downloads = await response.json();
setExistingDownloads(downloads);
// If we have a current jobId, show the new download view
if (jobId) {
setShowNewDownload(true);
}
} else {
console.error("Failed to fetch existing downloads");
}
} catch (error) {
console.error("Error fetching existing downloads:", error);
} finally {
setLoading(false);
}
};
fetchExistingDownloads();
}, [isOpen, dataroomId, teamId, jobId]);
const fetchStatus = useCallback(
async (statusJobId: string) => {
if (!statusJobId || !teamId || !dataroomId) return;
try {
const url = `/api/teams/${teamId}/datarooms/${dataroomId}/download/${statusJobId}`;
const response = await fetch(url, {
credentials: "include",
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || "Failed to fetch download status");
}
const data = await response.json();
setStatus(data);
setError(null);
// Stop polling when job is completed or failed
if (data.status === "COMPLETED" || data.status === "FAILED") {
setIsPolling(false);
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
}
} catch (err) {
setError(err instanceof Error ? err.message : "An error occurred");
setIsPolling(false);
}
},
[teamId, dataroomId],
);
// Start polling when we have a jobId and showNewDownload is true
useEffect(() => {
if (isOpen && jobId && showNewDownload) {
setIsPolling(true);
setStatus(null);
setError(null);
fetchStatus(jobId);
// Start polling interval
pollIntervalRef.current = setInterval(() => fetchStatus(jobId), 2000);
}
return () => {
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
};
}, [isOpen, jobId, showNewDownload, fetchStatus]);
const startNewDownload = async () => {
if (!teamId || !dataroomId) {
setError("Missing required parameters to start download");
return;
}
setIsStartingDownload(true);
setShowNewDownload(true);
try {
const endpoint = `/api/teams/${teamId}/datarooms/${dataroomId}/download/bulk`;
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || "Failed to start download");
}
if (data.jobId) {
// Start polling for this job
setStatus({
id: data.jobId,
status: data.status || "PENDING",
progress: 0,
totalFiles: 0,
processedFiles: 0,
isReady: false,
dataroomName: dataroomName || "",
createdAt: new Date().toISOString(),
});
setIsPolling(true);
const statusUrl = `/api/teams/${teamId}/datarooms/${dataroomId}/download/${data.jobId}`;
pollIntervalRef.current = setInterval(async () => {
const statusResponse = await fetch(statusUrl, {
credentials: "include",
});
if (statusResponse.ok) {
const statusData = await statusResponse.json();
setStatus(statusData);
if (
statusData.status === "COMPLETED" ||
statusData.status === "FAILED"
) {
setIsPolling(false);
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
}
}
}, 2000);
}
} catch (err) {
setError(err instanceof Error ? err.message : "An error occurred");
setShowNewDownload(false);
} finally {
setIsStartingDownload(false);
}
};
const handleDownload = (url: string) => {
const link = document.createElement("a");
link.href = url;
link.rel = "noopener noreferrer";
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
}, 100);
};
const handleDownloadAll = async (downloadId: string, urls: string[]) => {
if (downloadProgress) return;
setDownloadProgress({ downloadId, current: 0, total: urls.length });
for (let i = 0; i < urls.length; i++) {
setDownloadProgress({ downloadId, current: i + 1, total: urls.length });
handleDownload(urls[i]);
if (i < urls.length - 1) {
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
setDownloadProgress(null);
};
const handleClose = () => {
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
setStatus(null);
setError(null);
setIsPolling(false);
setShowNewDownload(false);
setExistingDownloads([]);
setExpandedDownloadId(null);
setLoading(true);
onClose();
};
const getStatusIcon = (jobStatus?: string) => {
switch (jobStatus) {
case "PENDING":
return (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
);
case "PROCESSING":
return <FileArchive className="h-4 w-4 animate-pulse text-primary" />;
case "COMPLETED":
return <CheckCircle2 className="h-4 w-4 text-green-500" />;
case "FAILED":
return <XCircle className="h-4 w-4 text-destructive" />;
default:
return (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
);
}
};
const getStatusColor = (jobStatus: string) => {
switch (jobStatus) {
case "COMPLETED":
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300";
case "PROCESSING":
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300";
case "PENDING":
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300";
case "FAILED":
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300";
default:
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300";
}
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString();
};
const formatExpirationTime = (expiresAt?: string) => {
if (!expiresAt) return null;
const expires = new Date(expiresAt);
const now = new Date();
const diffMs = expires.getTime() - now.getTime();
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffDays = Math.floor(diffHours / 24);
if (diffDays > 0) {
return `${diffDays} day${diffDays > 1 ? "s" : ""}`;
} else if (diffHours > 0) {
return `${diffHours} hour${diffHours > 1 ? "s" : ""}`;
}
return "less than an hour";
};
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
Download {dataroomName || status?.dataroomName || "Dataroom"}
</DialogTitle>
<DialogDescription>
{showNewDownload
? status?.status === "COMPLETED"
? "Your files are ready to download."
: "Please wait while we prepare your files..."
: "View previous downloads or start a new one."}
</DialogDescription>
</DialogHeader>
{loading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : showNewDownload ? (
// Show download progress
<div className="flex flex-col items-center space-y-4 py-6">
{/* Status Icon */}
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted">
{status?.status === "COMPLETED" ? (
<CheckCircle2 className="h-8 w-8 text-green-500" />
) : status?.status === "FAILED" ? (
<XCircle className="h-8 w-8 text-destructive" />
) : (
<FileArchive className="h-8 w-8 animate-pulse text-primary" />
)}
</div>
{/* Status Message */}
<p
className={cn(
"text-center text-sm",
status?.status === "FAILED"
? "text-destructive"
: "text-muted-foreground",
)}
>
{!status
? "Starting download..."
: status.status === "PENDING"
? "Preparing your download..."
: status.status === "PROCESSING"
? `Processing ${status.processedFiles} of ${status.totalFiles} files...`
: status.status === "COMPLETED"
? status.downloadUrls && status.downloadUrls.length > 1
? `Your download is ready! ${status.downloadUrls.length} ZIP files have been created.`
: "Your download is ready!"
: status.error || "Download failed. Please try again."}
</p>
{/* Progress Bar */}
{(status?.status === "PROCESSING" ||
status?.status === "PENDING") && (
<div className="w-full space-y-2">
<Progress
value={status?.progress || 0}
text={`${status?.progress || 0}%`}
className="h-4"
/>
<p className="text-center text-xs text-muted-foreground">
{status?.totalFiles
? `${status.processedFiles || 0} / ${status.totalFiles} files`
: "Calculating..."}
</p>
</div>
)}
{/* Download Links */}
{status?.status === "COMPLETED" && status.downloadUrls && (
<div className="w-full space-y-3">
{status.downloadUrls.length === 1 ? (
<Button
className="w-full"
onClick={() => handleDownload(status.downloadUrls![0])}
>
<Download className="mr-2 h-4 w-4" />
Download ZIP
</Button>
) : (
<>
<Button
className="w-full"
disabled={!!downloadProgress}
onClick={() =>
handleDownloadAll(status.id, status.downloadUrls!)
}
>
{downloadProgress?.downloadId === status.id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Downloading {downloadProgress.current} of{" "}
{downloadProgress.total}...
</>
) : (
<>
<Download className="mr-2 h-4 w-4" />
Download All ({status.downloadUrls.length} parts)
</>
)}
</Button>
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
Or download individually:
</p>
<div className="max-h-48 space-y-1 overflow-y-auto">
{status.downloadUrls.map((url, index) => (
<Button
key={index}
variant="outline"
size="sm"
className="w-full justify-start"
onClick={() => handleDownload(url)}
>
<FileArchive className="mr-2 h-3 w-3" />
Part {index + 1} of {status.downloadUrls!.length}
</Button>
))}
</div>
</div>
</>
)}
{/* Expiration Notice */}
{status.expiresAt && (
<div className="flex items-center justify-center gap-1 text-xs text-muted-foreground">
<AlertCircle className="h-3 w-3" />
<span>
Download expires in{" "}
{formatExpirationTime(status.expiresAt)}
</span>
</div>
)}
</div>
)}
{/* Error State */}
{status?.status === "FAILED" && (
<Button
variant="outline"
onClick={() => setShowNewDownload(false)}
>
Back to Downloads
</Button>
)}
{/* Back button for processing state */}
{(status?.status === "PROCESSING" ||
status?.status === "PENDING") && (
<DialogFooter className="w-full sm:justify-center">
<p className="text-xs text-muted-foreground">
You can close this dialog. We&apos;ll notify you when your
download is ready.
</p>
</DialogFooter>
)}
{/* Loading Error */}
{error && (
<div className="flex items-center gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4" />
<span>{error}</span>
</div>
)}
</div>
) : (
// Show existing downloads and new download option
<div className="space-y-4 py-2">
{existingDownloads.length > 0 ? (
<div className="space-y-3">
<h4 className="text-sm font-medium">Recent Downloads</h4>
<div className="max-h-64 space-y-2 overflow-y-auto">
{existingDownloads.map((download) => (
<div key={download.id} className="space-y-2">
<div className="flex items-center justify-between rounded-md border p-3">
<div className="flex-1 space-y-1">
<div className="flex items-center gap-2">
{getStatusIcon(download.status)}
<span
className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${getStatusColor(download.status)}`}
>
{download.status}
</span>
</div>
<div className="text-xs text-muted-foreground">
{formatDate(download.createdAt)}
</div>
{download.totalFiles > 0 && (
<div className="text-xs text-muted-foreground">
{download.totalFiles} files
{download.downloadUrls &&
download.downloadUrls.length > 1 &&
` (${download.downloadUrls.length} ZIPs)`}
</div>
)}
{download.expiresAt && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<AlertCircle className="h-3 w-3" />
Expires in{" "}
{formatExpirationTime(download.expiresAt)}
</div>
)}
{download.error && (
<p className="text-xs text-destructive">
{download.error}
</p>
)}
</div>
{download.status === "COMPLETED" &&
download.downloadUrls &&
download.downloadUrls.length > 0 &&
(download.downloadUrls.length === 1 ? (
<Button
size="sm"
onClick={() =>
handleDownload(download.downloadUrls![0])
}
>
<Download className="mr-1 h-3 w-3" />
Download
</Button>
) : (
<Button
size="sm"
variant="outline"
onClick={() =>
setExpandedDownloadId(
expandedDownloadId === download.id
? null
: download.id,
)
}
>
{expandedDownloadId === download.id ? (
<>
<ChevronUp className="mr-1 h-3 w-3" />
Hide
</>
) : (
<>
<ChevronDown className="mr-1 h-3 w-3" />
Show Downloads
</>
)}
</Button>
))}
{(download.status === "PENDING" ||
download.status === "PROCESSING") && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
{download.progress}%
</div>
)}
</div>
{/* Expanded download parts */}
{expandedDownloadId === download.id &&
download.downloadUrls &&
download.downloadUrls.length > 1 && (
<div className="space-y-2 rounded-md border bg-muted/30 p-3">
<Button
size="sm"
className="w-full"
disabled={!!downloadProgress}
onClick={() =>
handleDownloadAll(
download.id,
download.downloadUrls!,
)
}
>
{downloadProgress?.downloadId === download.id ? (
<>
<Loader2 className="mr-2 h-3 w-3 animate-spin" />
Downloading {downloadProgress.current} of{" "}
{downloadProgress.total}...
</>
) : (
<>
<Download className="mr-2 h-3 w-3" />
Download All ({download.downloadUrls.length}{" "}
parts)
</>
)}
</Button>
<p className="text-xs text-muted-foreground">
Or download individually:
</p>
<div className="max-h-32 space-y-1 overflow-y-auto">
{download.downloadUrls.map((url, index) => (
<Button
key={index}
variant="outline"
size="sm"
className="w-full justify-start"
onClick={() => handleDownload(url)}
>
<FileArchive className="mr-2 h-3 w-3" />
Part {index + 1} of{" "}
{download.downloadUrls!.length}
</Button>
))}
</div>
</div>
)}
</div>
))}
</div>
</div>
) : (
<div className="py-4 text-center text-sm text-muted-foreground">
No previous downloads found
</div>
)}
<div className="border-t pt-4">
<Button
className="w-full"
onClick={startNewDownload}
disabled={isStartingDownload}
>
{isStartingDownload ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
Start New Download
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -1,138 +0,0 @@
import { useRouter } from "next/router";
import { useState } from "react";
import { useTeam } from "@/context/team-context";
import { toast } from "sonner";
import { mutate } from "swr";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export function EditDataroomDocumentModal({
open,
setOpen,
documentId,
documentName,
dataroomId,
}: {
open: boolean;
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
documentId: string;
documentName: string;
dataroomId: string;
}) {
const [name, setName] = useState<string>(documentName);
const [loading, setLoading] = useState<boolean>(false);
const teamInfo = useTeam();
const router = useRouter();
const currentFolderPath = router.query.name as string[] | undefined;
const editDocumentNameSchema = z.object({
name: z
.string()
.min(1, {
message: "Please provide a document name.",
})
.max(255, {
message: "Document name is too long.",
}),
});
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
event.stopPropagation();
const validation = editDocumentNameSchema.safeParse({ name });
if (!validation.success) {
return toast.error(validation.error.errors[0].message);
}
setLoading(true);
try {
const response = await fetch(
`/api/teams/${teamInfo?.currentTeam?.id}/documents/${documentId}/update-name`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: name.trim(),
}),
},
);
if (!response.ok) {
const { error, message } = await response.json();
setLoading(false);
toast.error(error || message || "Failed to update document name");
return;
}
toast.success("Document name updated successfully!");
// Revalidate the dataroom documents cache
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
);
// Revalidate folder documents if the document is in a folder
if (currentFolderPath) {
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${currentFolderPath.join("/")}`,
);
}
// Revalidate the dataroom folders tree for sidebar
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders?tree=true`,
);
} catch (error) {
setLoading(false);
toast.error("Error updating document name. Please try again.");
return;
} finally {
setLoading(false);
setOpen(false);
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader className="text-start">
<DialogTitle>Rename Document</DialogTitle>
<DialogDescription>Enter a new document name.</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit}>
<Label htmlFor="document-name-update" className="opacity-80">
Document Name
</Label>
<Input
id="document-name-update"
value={name}
placeholder="document-name"
className="mb-4 mt-1 w-full"
onChange={(e) => setName(e.target.value)}
/>
<DialogFooter>
<Button type="submit" className="h-9 w-full" loading={loading}>
Update name
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -1,766 +0,0 @@
"use client";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useTeam } from "@/context/team-context";
import { BookOpenIcon, EyeIcon } from "lucide-react";
import { toast } from "sonner";
import { mutate } from "swr";
import { usePlan } from "@/lib/swr/use-billing";
import { uploadImage } from "@/lib/utils";
import PlanBadge from "@/components/billing/plan-badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import LoadingSpinner from "@/components/ui/loading-spinner";
import { RichTextEditor } from "@/components/ui/rich-text-editor";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Switch } from "@/components/ui/switch";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
interface IntroductionSettingsProps {
dataroomId: string;
}
interface FolderItem {
id: string;
name: string;
documents?: { document: { name: string } }[];
}
interface DocumentItem {
document: { name: string };
}
// Generate TipTap JSON content for introduction based on dataroom structure
function generateIntroductionContent(
dataroomName: string,
folders: FolderItem[],
rootDocuments: DocumentItem[],
): any {
const content: any[] = [];
// Overview paragraph (no "Welcome to" repetition)
content.push({
type: "paragraph",
content: [
{
type: "text",
text: `This data room contains confidential documents and materials prepared for your review. Please take a moment to familiarize yourself with the structure below.`,
},
],
});
// What's Inside section
content.push({
type: "heading",
attrs: { level: 2 },
content: [{ type: "text", text: "What's Inside" }],
});
// If there are folders, list them
if (folders.length > 0) {
const folderList = {
type: "bulletList",
content: folders.slice(0, 8).map((folder) => ({
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: folder.name,
marks: [{ type: "bold" }],
},
...(folder.documents && folder.documents.length > 0
? [
{
type: "text",
text: `${folder.documents.length} document${folder.documents.length > 1 ? "s" : ""}`,
},
]
: []),
],
},
],
})),
};
content.push(folderList);
if (folders.length > 8) {
content.push({
type: "paragraph",
content: [
{
type: "text",
text: `...and ${folders.length - 8} more sections.`,
},
],
});
}
} else {
// Show placeholder sections if dataroom is empty
const placeholderList = {
type: "bulletList",
content: [
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "Section 1", marks: [{ type: "bold" }] },
{ type: "text", text: " — Company Overview & Key Documents" },
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "Section 2", marks: [{ type: "bold" }] },
{ type: "text", text: " — Financial Information" },
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "Section 3", marks: [{ type: "bold" }] },
{ type: "text", text: " — Legal & Compliance" },
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "Section 4", marks: [{ type: "bold" }] },
{ type: "text", text: " — Additional Materials" },
],
},
],
},
],
};
content.push(placeholderList);
}
// If there are root documents, mention them
if (rootDocuments.length > 0) {
content.push({
type: "paragraph",
content: [
{
type: "text",
text: `There ${rootDocuments.length === 1 ? "is" : "are"} also ${rootDocuments.length} document${rootDocuments.length > 1 ? "s" : ""} available at the root level for quick access.`,
},
],
});
}
// How to Navigate section
content.push({
type: "heading",
attrs: { level: 2 },
content: [{ type: "text", text: "How to Navigate" }],
});
content.push({
type: "bulletList",
content: [
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Use the sidebar on the left to browse sections and folders",
},
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Click on any document to open and view it",
},
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Use the search function to find specific documents quickly",
},
],
},
],
},
],
});
// Placeholder for navigation screenshot
// Q&A and Conversations section
content.push({
type: "heading",
attrs: { level: 2 },
content: [{ type: "text", text: "Q&A and Conversations" }],
});
content.push({
type: "paragraph",
content: [
{
type: "text",
text: "Have questions about specific documents? You can start a conversation directly within the data room. Use the chat feature to ask questions and get answers from our team.",
},
],
});
content.push({
type: "bulletList",
content: [
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Click the chat icon to start a new conversation",
},
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Ask questions about any document or section",
},
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Receive timely responses from our team",
},
],
},
],
},
],
});
// Placeholder for conversations screenshot
// Need Help section
content.push({
type: "heading",
attrs: { level: 2 },
content: [{ type: "text", text: "Need Help?" }],
});
content.push({
type: "paragraph",
content: [
{
type: "text",
text: "If you have any questions or need assistance, please reach out to your designated contact. We're here to help you navigate this data room effectively.",
},
],
});
return {
type: "doc",
content,
};
}
// Helper to render inline text nodes with marks (bold, italic, etc.)
function renderInlineContent(nodes: any[] | undefined): React.ReactNode {
if (!nodes) return null;
return nodes.map((textNode: any, textIndex: number) => {
if (textNode.type === "text") {
let text: React.ReactNode = textNode.text;
if (textNode.marks) {
textNode.marks.forEach((mark: any) => {
if (mark.type === "bold") {
text = (
<strong key={`bold-${textIndex}`} className="font-semibold">
{text}
</strong>
);
} else if (mark.type === "italic") {
text = (
<em key={`italic-${textIndex}`} className="italic">
{text}
</em>
);
}
});
}
return <React.Fragment key={textIndex}>{text}</React.Fragment>;
} else if (textNode.type === "image") {
return (
<img
key={textIndex}
src={textNode.attrs?.src}
alt={textNode.attrs?.alt || ""}
className="my-2 h-auto max-w-full rounded-md"
/>
);
}
return null;
});
}
// Render TipTap JSON content for preview
function renderContent(content: any): React.ReactNode {
if (!content || !content.content) return null;
return content.content.map((node: any, index: number) => {
if (node.type === "heading") {
const level = node.attrs?.level || 1;
const text = node.content?.[0]?.text || "";
if (level === 1) {
return (
<h1
key={index}
className="mb-3 mt-4 text-xl font-bold text-gray-900 first:mt-0"
>
{text}
</h1>
);
}
return (
<h2
key={index}
className="mb-2 mt-4 text-base font-semibold text-gray-800 first:mt-0"
>
{text}
</h2>
);
} else if (node.type === "paragraph") {
return (
<p key={index} className="mb-3 text-sm leading-relaxed text-gray-700">
{renderInlineContent(node.content)}
</p>
);
} else if (node.type === "bulletList") {
return (
<ul key={index} className="mb-3 list-disc pl-5 text-sm text-gray-700">
{node.content?.map((item: any, itemIndex: number) => (
<li key={itemIndex} className="mb-1">
{renderInlineContent(item.content?.[0]?.content)}
</li>
))}
</ul>
);
} else if (node.type === "orderedList") {
return (
<ol
key={index}
className="mb-3 list-decimal pl-5 text-sm text-gray-700"
>
{node.content?.map((item: any, itemIndex: number) => (
<li key={itemIndex} className="mb-1">
{renderInlineContent(item.content?.[0]?.content)}
</li>
))}
</ol>
);
} else if (node.type === "blockquote") {
return (
<blockquote
key={index}
className="mb-3 border-l-4 border-gray-300 pl-4 italic text-gray-600"
>
{node.content?.map((p: any) =>
p.content?.map((textNode: any) =>
textNode.type === "text" ? textNode.text : null,
),
)}
</blockquote>
);
} else if (node.type === "image") {
return (
<img
key={index}
src={node.attrs?.src}
alt={node.attrs?.alt || ""}
className="my-3 h-auto max-w-full rounded-md"
/>
);
} else if (node.type === "youtube") {
// Extract video ID from the src URL
const src = node.attrs?.src || "";
let videoId = "";
// Handle different YouTube URL formats
const youtubeMatch = src.match(
/(?:youtube(?:-nocookie)?\.com\/(?:embed\/|watch\?v=)|youtu\.be\/)([^?&]+)/,
);
if (youtubeMatch) {
videoId = youtubeMatch[1];
}
if (!videoId) return null;
return (
<div key={index} className="my-4 aspect-video w-full">
<iframe
src={`https://www.youtube-nocookie.com/embed/${videoId}`}
title="YouTube video"
className="h-full w-full rounded-lg"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
/>
</div>
);
}
return null;
});
}
export default function IntroductionSettings({
dataroomId,
}: IntroductionSettingsProps) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
const { isDataroomsPlus, isTrial } = usePlan();
const [isFetching, setIsFetching] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [introductionEnabled, setIntroductionEnabled] = useState(false);
const [introductionContent, setIntroductionContent] = useState<any>({
type: "doc",
content: [],
});
const [showPreview, setShowPreview] = useState(false);
const [dataroomName, setDataroomName] = useState<string>("Data Room");
const isFeatureAvailable = isDataroomsPlus || isTrial;
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const hasInitialLoadRef = useRef(false);
const skipNextAutosaveRef = useRef(false);
// Fetch current introduction settings from dataroom
useEffect(() => {
const fetchSettings = async () => {
if (!teamId) return;
try {
const response = await fetch(
`/api/teams/${teamId}/datarooms/${dataroomId}`,
);
if (response.ok) {
const data = await response.json();
setIntroductionEnabled(data.introductionEnabled || false);
setDataroomName(data.name || "Data Room");
const existingContent = data.introductionContent;
const hasExistingContent =
existingContent?.content && existingContent.content.length > 0;
if (hasExistingContent) {
setIntroductionContent(existingContent);
} else {
// Auto-generate introduction if empty
try {
const foldersResponse = await fetch(
`/api/teams/${teamId}/datarooms/${dataroomId}/folders?include_documents=true`,
);
let folders: FolderItem[] = [];
let rootDocuments: DocumentItem[] = [];
if (foldersResponse.ok) {
const foldersData = await foldersResponse.json();
folders = foldersData.filter(
(item: any) => item.name && !item.document,
);
rootDocuments = foldersData.filter(
(item: any) => item.document,
);
}
const generatedContent = generateIntroductionContent(
data.name || "Data Room",
folders,
rootDocuments,
);
setIntroductionContent(generatedContent);
} catch (genError) {
console.error("Failed to auto-generate introduction:", genError);
setIntroductionContent({ type: "doc", content: [] });
}
}
}
} catch (error) {
console.error("Failed to fetch introduction settings:", error);
} finally {
setIsFetching(false);
hasInitialLoadRef.current = true;
skipNextAutosaveRef.current = true;
}
};
fetchSettings();
}, [teamId, dataroomId]);
// Auto-save function
const saveSettings = useCallback(
async (enabled: boolean, content: any) => {
if (!teamId || !isFeatureAvailable) return;
setIsSaving(true);
try {
const response = await fetch(
`/api/teams/${teamId}/datarooms/${dataroomId}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
introductionEnabled: enabled,
introductionContent: content,
}),
},
);
if (response.ok) {
await mutate(`/api/teams/${teamId}/datarooms/${dataroomId}`);
} else {
toast.error("Failed to save introduction settings");
}
} catch (error) {
console.error("Failed to save introduction settings:", error);
toast.error("Failed to save introduction settings");
} finally {
setIsSaving(false);
}
},
[teamId, dataroomId, isFeatureAvailable],
);
// Debounced auto-save on content change
useEffect(() => {
if (!hasInitialLoadRef.current) return;
// Skip the first auto-save pass after initial load
if (skipNextAutosaveRef.current) {
skipNextAutosaveRef.current = false;
return;
}
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
}
saveTimeoutRef.current = setTimeout(() => {
saveSettings(introductionEnabled, introductionContent);
}, 1000);
return () => {
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
}
};
}, [introductionContent, introductionEnabled, saveSettings]);
const handleImageUpload = async (file: File): Promise<string> => {
try {
const imageUrl = await uploadImage(file, "assets");
return imageUrl;
} catch (error) {
console.error("Failed to upload image:", error);
throw new Error("Failed to upload image");
}
};
const handleToggle = (checked: boolean) => {
if (!isFeatureAvailable) {
toast.error("This feature is only available on Data Rooms Plus plan");
return;
}
setIntroductionEnabled(checked);
if (checked) {
toast.success("Introduction page enabled");
}
};
const hasContent =
introductionContent?.content && introductionContent.content.length > 0;
if (isFetching) {
return (
<Card className="bg-transparent">
<CardContent className="flex items-center justify-center py-10">
<LoadingSpinner className="h-6 w-6" />
</CardContent>
</Card>
);
}
return (
<Card className="bg-transparent">
<CardHeader>
<CardTitle className="flex items-center gap-2">
Introduction Page{" "}
{!isFeatureAvailable && <PlanBadge plan="data rooms plus" />}
{isSaving && (
<span className="text-xs font-normal text-muted-foreground">
Saving...
</span>
)}
</CardTitle>
<CardDescription>
Create an introduction page that will be shown to viewers when they
first access your data room. Write your message based on the premade
template below. You can edit, add and remove sections as you see fit.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Toggle and Preview */}
<div className="flex items-center justify-between">
<Label
htmlFor="introduction-toggle"
className="flex items-center gap-2"
>
<BookOpenIcon className="h-4 w-4" />
Show introduction on first visit
</Label>
<div className="flex items-center gap-2">
<TooltipProvider delayDuration={0}>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() => setShowPreview(true)}
disabled={!hasContent}
className="h-8 w-8"
>
<EyeIcon className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>Preview introduction</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<Switch
id="introduction-toggle"
checked={introductionEnabled}
onCheckedChange={handleToggle}
disabled={!isFeatureAvailable}
/>
</div>
</div>
{/* Rich Text Editor */}
<div className="space-y-2">
<RichTextEditor
content={introductionContent}
onChange={setIntroductionContent}
placeholder="Welcome to our data room! Here you'll find..."
onImageUpload={handleImageUpload}
/>
</div>
{/* Preview Dialog */}
<Dialog open={showPreview} onOpenChange={setShowPreview}>
<DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden border-0 p-0 shadow-2xl sm:max-w-xl sm:rounded-2xl md:max-w-2xl">
<DialogHeader className="border-b border-gray-100 bg-gray-50 px-4 py-6 dark:border-gray-800 dark:bg-gray-900 sm:px-6">
<p className="mb-1 text-xs text-muted-foreground">
This is a preview
</p>
<DialogTitle className="text-xl font-semibold">
Welcome to {dataroomName}
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[55vh] px-4 py-5 sm:px-6">
<div className="prose prose-sm max-w-none dark:prose-invert">
{renderContent(introductionContent)}
</div>
</ScrollArea>
<div className="flex justify-end border-t border-gray-100 bg-gray-50 px-4 py-3 dark:border-gray-800 dark:bg-gray-900 sm:px-6 sm:py-4">
<Button onClick={() => setShowPreview(false)}>
Continue to Data Room
</Button>
</div>
</DialogContent>
</Dialog>
</CardContent>
<CardFooter className="flex items-center rounded-b-lg border-t bg-muted px-6 py-4">
<p className="text-sm text-muted-foreground">
This page will appear as a welcome popup when visitors first open the
data room. Changes are saved automatically.
</p>
</CardFooter>
</Card>
);
}
@@ -1,13 +1,7 @@
import Link from "next/link";
import { useRouter } from "next/router";
import {
BellIcon,
BookOpenIcon,
CogIcon,
DownloadIcon,
ShieldIcon,
} from "lucide-react";
import { BellIcon, CogIcon, DownloadIcon, ShieldIcon } from "lucide-react";
import { cn } from "@/lib/utils";
@@ -33,18 +27,6 @@ export default function SettingsTabs({ dataroomId }: SettingsTabsProps) {
<CogIcon className="h-4 w-4" />
General
</Link>
<Link
href={`/datarooms/${dataroomId}/settings/introduction`}
className={cn(
"flex items-center gap-x-2 rounded-md p-2 text-primary hover:bg-muted",
{
"bg-muted font-medium": router.pathname.includes("introduction"),
},
)}
>
<BookOpenIcon className="h-4 w-4" />
Introduction
</Link>
<Link
href={`/datarooms/${dataroomId}/settings/notifications`}
className={cn(
+2 -13
View File
@@ -8,6 +8,7 @@ import {
ClipboardCopyIcon,
CopyIcon,
EyeOffIcon,
FolderIcon,
FolderInputIcon,
FolderPenIcon,
MoreVertical,
@@ -17,7 +18,6 @@ import {
import { toast } from "sonner";
import { mutate } from "swr";
import { getFolderColorClasses, getFolderIcon } from "@/lib/constants/folder-constants";
import { DataroomFolderWithCount } from "@/lib/swr/use-dataroom";
import { FolderWithCount } from "@/lib/swr/use-documents";
import { timeAgo } from "@/lib/utils";
@@ -200,16 +200,7 @@ export default function FolderCard({
<div className="flex min-w-0 shrink items-center space-x-2 sm:space-x-4">
{!isSelected && !isHovered ? (
<div className="mx-0.5 flex w-8 items-center justify-center text-center sm:mx-1">
{(() => {
const FolderIconComponent = getFolderIcon(folder.icon);
const colorClasses = getFolderColorClasses(folder.color);
return (
<FolderIconComponent
className={`h-8 w-8 ${colorClasses.iconClass}`}
strokeWidth={1}
/>
);
})()}
<FolderIcon className="h-8 w-8" strokeWidth={1} />
</div>
) : (
<div className="mx-0.5 w-8 sm:mx-1"></div>
@@ -364,8 +355,6 @@ export default function FolderCard({
setOpen={setOpenFolder}
folderId={folder.id}
name={folder.name}
icon={folder.icon}
color={folder.color}
isDataroom={isDataroom}
dataroomId={dataroomId}
/>
+60 -276
View File
@@ -1,21 +1,14 @@
import { useEffect, useRef, useState, type ElementType } from "react";
import { useState } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
import { LinkType } from "@prisma/client";
import {
AlertTriangleIcon,
CircleCheckIcon,
InfoIcon,
} from "lucide-react";
import { toast } from "sonner";
import { useDebounce } from "use-debounce";
import { z } from "zod";
import { useAnalytics } from "@/lib/analytics";
import { validDomainRegex } from "@/lib/domains";
import { usePlan } from "@/lib/swr/use-billing";
import useLimits from "@/lib/swr/use-limits";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
@@ -29,71 +22,10 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import LoadingSpinner from "@/components/ui/loading-spinner";
import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
import { UpgradeButton } from "../ui/upgrade-button";
const sanitizeDomain = (value: string) =>
value
.trim()
.toLowerCase()
.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "")
.split("/")[0];
type DomainStatus =
| "checking"
| "has site"
| "available"
| "idle"
| "invalid"
| "error";
const STATUS_CONFIG: Record<
DomainStatus,
{
prefix?: string;
useStrong?: boolean;
suffix?: string;
icon?: ElementType;
className?: string;
message?: string;
}
> = {
checking: {
prefix: "Checking availability for",
useStrong: true,
suffix: "...",
icon: LoadingSpinner,
className: "bg-neutral-100 text-neutral-500",
},
"has site": {
suffix:
"is currently pointing to an existing website. Only proceed if you're sure you want to use this domain for Papermark links.",
icon: InfoIcon,
className: "bg-blue-100 text-blue-800",
},
available: {
suffix: "is ready to connect.",
icon: CircleCheckIcon,
className: "bg-emerald-100 text-emerald-600",
},
invalid: {
message: "Enter a valid domain to check availability.",
icon: AlertTriangleIcon,
className: "bg-rose-100 text-rose-600",
},
idle: {
message: "Enter a valid domain to check availability.",
className: "bg-neutral-100 text-neutral-500",
},
error: {
message: "We couldn't check this domain right now. Try again.",
icon: AlertTriangleIcon,
className: "bg-rose-100 text-rose-600",
},
};
export function AddDomainModal({
open,
setOpen,
@@ -107,154 +39,69 @@ export function AddDomainModal({
linkType?: Omit<LinkType, "WORKFLOW_LINK">;
children?: React.ReactNode;
}) {
const [domainInput, setDomainInput] = useState<string>("");
const [submitting, setSubmitting] = useState<boolean>(false);
const [domainStatus, setDomainStatus] = useState<DomainStatus>("idle");
const [statusMessageOverride, setStatusMessageOverride] = useState<
string | null
>(null);
const abortRef = useRef<AbortController | null>(null);
const [domain, setDomain] = useState<string>("");
const [loading, setLoading] = useState<boolean>(false);
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
const { isFree, isPro, isBusiness } = usePlan();
const { limits } = useLimits();
const analytics = useAnalytics();
useEffect(() => {
if (!open) {
setDomainInput("");
setSubmitting(false);
setDomainStatus("idle");
setStatusMessageOverride(null);
}
}, [open]);
const sanitizedDomain = sanitizeDomain(domainInput);
const [debouncedDomain] = useDebounce(sanitizedDomain, 500);
useEffect(() => {
if (!open) return;
if (!teamId) return;
if (!debouncedDomain) {
setDomainStatus("idle");
setStatusMessageOverride(null);
return;
}
if (debouncedDomain.includes("papermark")) {
setDomainStatus("invalid");
setStatusMessageOverride("Domain cannot contain 'papermark'.");
return;
}
if (!validDomainRegex.test(debouncedDomain)) {
setDomainStatus("idle");
setStatusMessageOverride(null);
return;
}
// Abort any in-flight validation request before starting a new one
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setDomainStatus("checking");
setStatusMessageOverride(null);
fetch(
`/api/teams/${teamId}/domains/${encodeURIComponent(
debouncedDomain,
)}/validate`,
{ signal: controller.signal },
)
.then(async (res) => res.json())
.then((data) => {
const nextStatus = data?.status as DomainStatus | undefined;
if (
nextStatus &&
["invalid", "has site", "available"].includes(nextStatus)
) {
setDomainStatus(nextStatus);
} else {
setDomainStatus("error");
}
const addDomainSchema = z.object({
name: z
.string()
.min(3, {
message: "Please provide a domain name with at least 3 characters.",
})
.catch((err) => {
// Ignore aborted requests they are expected when the user types again
if ((err as DOMException).name === "AbortError") return;
setDomainStatus("error");
});
return () => {
controller.abort();
abortRef.current = null;
};
}, [debouncedDomain, open, teamId]);
const saveDisabled =
!["available", "has site"].includes(domainStatus) || submitting;
// Add validation for papermark
.refine((name) => !name.toLowerCase().includes("papermark"), {
message: "Domain cannot contain 'papermark'",
}),
});
const handleSubmit = async (event: any) => {
event.preventDefault();
event.stopPropagation();
const normalizedDomain = sanitizeDomain(domainInput);
if (!normalizedDomain || !validDomainRegex.test(normalizedDomain)) {
return toast.error("Please enter a valid domain (e.g., example.com).");
const validation = addDomainSchema.safeParse({ name: domain });
if (!validation.success) {
return toast.error(validation.error.errors[0].message);
}
if (normalizedDomain.includes("papermark")) {
return toast.error("Domain cannot contain 'papermark'.");
}
if (saveDisabled) {
return toast.error(
statusMessageOverride ??
"Please enter a valid domain before adding.",
);
}
setSubmitting(true);
try {
const response = await fetch(
`/api/teams/${teamId}/domains`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
domain: normalizedDomain,
}),
setLoading(true);
const response = await fetch(
`/api/teams/${teamInfo?.currentTeam?.id}/domains`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
);
if (!response.ok) {
const { message } = await response.json();
toast.error(message);
return;
}
const newDomain = await response.json();
analytics.capture("Domain Added", { slug: normalizedDomain });
toast.success("Domain added successfully! 🎉");
// Update local data with the new link
onAddition && onAddition(newDomain);
body: JSON.stringify({
domain: domain,
}),
},
);
if (!response.ok) {
const { message } = await response.json();
setLoading(false);
setOpen(false);
!onAddition && window.open("/settings/domains", "_blank");
} catch (error: unknown) {
const message =
error instanceof Error ? error.message : "An unknown error occurred";
toast.error(`Failed to add domain: ${message}`);
} finally {
setSubmitting(false);
toast.error(message);
return;
}
const newDomain = await response.json();
analytics.capture("Domain Added", { slug: domain });
toast.success("Domain added successfully! 🎉");
// Update local data with the new link
onAddition && onAddition(newDomain);
setOpen(false);
setLoading(false);
!onAddition && window.open("/settings/domains", "_blank");
};
// If the team is
@@ -302,89 +149,26 @@ export function AddDomainModal({
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent className="sm:max-w-[520px]">
<DialogContent className="sm:max-w-[425px]">
<DialogHeader className="text-start">
<DialogTitle>Add Domain</DialogTitle>
<DialogDescription>
Add a custom domain and verify it with DNS.
You can easily add a custom domain.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit}>
<Label htmlFor="domain" className="opacity-80">
Your domain
Domain
</Label>
{(() => {
const currentStatus = STATUS_CONFIG[domainStatus];
const StatusIcon = currentStatus.icon;
return (
<div
className={cn(
"-m-1 mt-2 rounded-[0.625rem] p-1",
currentStatus.className || "bg-neutral-100 text-neutral-500",
)}
>
<div className="flex rounded-md border border-neutral-300 bg-white">
<Input
id="domain"
placeholder="docs.yourdomain.com"
className="border-0 bg-transparent shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
value={domainInput}
onBlur={() => {
const normalized = sanitizeDomain(domainInput);
if (normalized && normalized !== domainInput) {
setDomainInput(normalized);
}
}}
onChange={(e) => {
// Cancel any in-flight validation so stale results
// don't overwrite the reset status below
abortRef.current?.abort();
abortRef.current = null;
setDomainStatus("idle");
setStatusMessageOverride(null);
setDomainInput(e.target.value);
}}
/>
</div>
<div className="flex items-center justify-between gap-4 p-2 text-sm">
<p>
{["checking", "has site", "available"].includes(
domainStatus,
) ? (
<>
{currentStatus.prefix || "The domain"}{" "}
{currentStatus.useStrong ? (
<strong className="font-semibold underline underline-offset-2">
{sanitizedDomain || "this domain"}
</strong>
) : (
<span className="font-semibold underline underline-offset-2">
{sanitizedDomain || "this domain"}
</span>
)}{" "}
{currentStatus.suffix}
</>
) : (
statusMessageOverride ||
currentStatus.message ||
"Enter a valid domain to check availability."
)}
</p>
{StatusIcon && (
<StatusIcon className="h-5 w-5 shrink-0" />
)}
</div>
</div>
);
})()}
<DialogFooter className="mt-6">
<Button
type="submit"
className="h-9 w-full"
disabled={saveDisabled}
>
{submitting ? "Adding domain..." : "Add domain"}
<Input
id="domain"
placeholder="docs.yourdomain.com"
className="mb-8 mt-1 w-full"
onChange={(e) => setDomain(e.target.value)}
/>
<DialogFooter>
<Button type="submit" className="h-9 w-full">
Add domain
</Button>
</DialogFooter>
</form>
+5 -13
View File
@@ -9,27 +9,19 @@ import {
} from "@/lib/types";
import { fetcher } from "@/lib/utils";
export function useDomainStatus({
domain,
enabled = true,
}: {
domain: string;
enabled?: boolean;
}) {
export function useDomainStatus({ domain }: { domain: string }) {
const teamInfo = useTeam();
const key =
enabled && domain
? `/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`
: null;
const { data, isValidating, mutate } = useSWR<{
status: DomainVerificationStatusProps;
response: {
domainJson: DomainResponse & { error: { code: string; message: string } };
configJson: DomainConfigResponse;
};
}>(key, fetcher);
}>(
`/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`,
fetcher,
);
return {
status: data?.status,
+49
View File
@@ -0,0 +1,49 @@
import {
Body,
Head,
Html,
Link,
Tailwind,
Text,
} from "@react-email/components";
interface AbandonedCheckoutEmailProps {
name: string | null | undefined;
}
const AbandonedCheckoutEmail = ({ name }: AbandonedCheckoutEmailProps) => {
return (
<Html>
<Head />
<Tailwind>
<Body className="font-sans text-sm">
<Text>Hi{name && ` ${name}`},</Text>
<Text>
I noticed you started the checkout process but didn&apos;t complete
it. Did something go wrong?
</Text>
<Text>
If you ran into any issues or have questions about our plans,
I&apos;d be happy to help. Just reply to this email.
</Text>
<Text>
<Link
href="https://app.papermark.com/settings/upgrade"
target="_blank"
className="text-blue-500 underline"
>
Complete your upgrade
</Link>
</Text>
<Text>
Best,
<br />
Marc
</Text>
</Body>
</Tailwind>
</Html>
);
};
export default AbandonedCheckoutEmail;
@@ -1,103 +0,0 @@
import React from "react";
import {
Body,
Button,
Container,
Head,
Html,
Preview,
Section,
Tailwind,
Text,
} from "@react-email/components";
import { Footer } from "./shared/footer";
export default function DataroomUploadNotification({
dataroomId = "123",
dataroomName = "Example Dataroom",
uploaderEmail = "visitor@example.com",
documentNames = ["Document 1.pdf", "Document 2.pdf"],
linkName = "Link #abc12",
}: {
dataroomId: string;
dataroomName: string;
uploaderEmail: string | null;
documentNames: string[];
linkName: string;
}) {
const documentCount = documentNames.length;
const documentLabel = documentCount === 1 ? "document" : "documents";
return (
<Html>
<Head />
<Preview>
{`${documentCount} new ${documentLabel} uploaded to ${dataroomName}`}
</Preview>
<Tailwind>
<Body className="mx-auto my-auto bg-white font-sans">
<Container className="mx-auto my-10 w-[465px] p-5">
<Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
<span className="font-bold tracking-tighter">Papermark</span>
</Text>
<Text className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
New File Upload
</Text>
<Text className="text-sm leading-6 text-black">
{uploaderEmail ? (
<>
<span className="font-semibold">{uploaderEmail}</span> has
uploaded{" "}
</>
) : (
<>A visitor has uploaded </>
)}
<span className="font-semibold">
{documentCount} {documentLabel}
</span>{" "}
to your dataroom{" "}
<span className="font-semibold">{dataroomName}</span> via the link{" "}
<span className="font-semibold">{linkName}</span>.
</Text>
{documentNames.length <= 10 && (
<Section className="my-4">
{documentNames.map((name, index) => (
<Text
key={index}
className="my-1 text-sm leading-6 text-black"
>
{"\u2022"} {name}
</Text>
))}
</Section>
)}
<Section className="my-8 text-center">
<Button
className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
href={`https://app.papermark.com/datarooms/${dataroomId}`}
style={{ padding: "12px 20px" }}
>
View the dataroom
</Button>
</Section>
<Footer
footerText={
<>
If you have any feedback or questions about this email, simply
reply to it. I&apos;d love to hear from you!
<br />
<br />
To stop email notifications for this link, edit the link and
uncheck &quot;Receive email notification&quot;.
</>
}
/>
</Container>
</Body>
</Tailwind>
</Html>
);
}
-108
View File
@@ -1,108 +0,0 @@
import {
Body,
Button,
Container,
Head,
Html,
Preview,
Section,
Tailwind,
Text,
} from "@react-email/components";
import { Footer } from "./shared/footer";
function formatExpirationTime(expiresAt?: string): string {
if (!expiresAt) return "3 days";
const expires = new Date(expiresAt);
const now = new Date();
const diffMs = expires.getTime() - now.getTime();
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffDays = Math.floor(diffHours / 24);
if (diffDays > 0) {
return `${diffDays} day${diffDays > 1 ? "s" : ""}`;
} else if (diffHours > 0) {
return `${diffHours} hour${diffHours > 1 ? "s" : ""}`;
}
return "less than an hour";
}
export default function DownloadReady({
dataroomName = "Dataroom",
downloadUrl = "https://app.papermark.com",
email = "email@example.com",
expiresAt,
isViewer = false,
}: {
dataroomName?: string;
downloadUrl?: string;
email: string;
expiresAt?: string;
isViewer?: boolean;
}) {
const expirationTime = formatExpirationTime(expiresAt);
return (
<Html>
<Head />
<Preview>Your {dataroomName} download is ready</Preview>
<Tailwind>
<Body className="mx-auto my-auto bg-white font-sans">
<Container className="mx-auto my-10 w-[465px] p-5">
<Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
<span className="font-bold tracking-tighter">Papermark</span>
</Text>
<Text className="text-sm leading-6 text-black">
Your download of <strong>{dataroomName}</strong> is ready!
</Text>
<Text className="text-sm leading-6 text-black">
{isViewer
? "Click the button below to open your downloads page and get your files."
: "Click the button below to download your files. You'll need to be logged in to your Papermark account to access the download."}
</Text>
<Section className="my-8 text-center">
<Button
className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
href={downloadUrl}
style={{ padding: "12px 20px" }}
>
Download Files
</Button>
</Section>
<Text className="text-sm leading-6 text-black">
Download details:
</Text>
<ul className="break-all text-sm leading-6 text-black">
<li className="text-sm leading-6 text-black">
Dataroom: {dataroomName}
</li>
<li className="text-sm leading-6 text-black">
Expires: in {expirationTime}
</li>
</ul>
<Text className="text-sm leading-6 text-black">
Best,
<br />
The Papermark Team
</Text>
<Footer
footerText={
<>
This email was intended for{" "}
<span className="text-black">{email}</span>. If you were not
expecting this email, you can ignore this email. If you have
any feedback or questions about this email, simply reply to
it.
</>
}
/>
</Container>
</Body>
</Tailwind>
</Html>
);
}
+118
View File
@@ -0,0 +1,118 @@
import {
Body,
Head,
Html,
Link,
Tailwind,
Text,
} from "@react-email/components";
// Map trigger names to feature titles
const FEATURE_NAMES: Record<string, string> = {
// Custom domains
add_domain_overview: "Custom Domains",
add_domain_link_sheet: "Custom Domains",
// Data rooms
datarooms: "Secure Data Rooms",
add_dataroom_overview: "Secure Data Rooms",
datarooms_generate_index_button: "Data Room Index",
datarooms_rebuild_index_button: "Data Room Index",
// Team features
invite_team_members: "Team Collaboration",
add_new_team: "Multiple Teams",
// Visitor analytics
"visitor-table-user-agent": "Visitor Analytics",
// Tags
create_tag: "Document Tags",
// Folders
add_folder_button: "Folders",
// Document limits
limit_upload_documents: "Unlimited Documents",
limit_upload_document_version: "Document Versions",
// Link limits
limit_add_link: "Unlimited Links",
// Analytics exports
dashboard_visitors_export: "Analytics Export",
dashboard_views_export: "Analytics Export",
dashboard_links_export: "Analytics Export",
dashboard_documents_export: "Analytics Export",
dashboard_time_range_custom_select: "Custom Date Ranges",
// Branding
pro_banner: "Custom Branding",
// Web links
add_web_link_document: "Web Links",
// Groups
add_group_link: "Link Groups",
};
// Get unique feature names from triggers (deduplicated, lowercase)
function getUniqueFeatureNames(triggers: string[]): string[] {
const seenTitles = new Set<string>();
const featureNames: string[] = [];
for (const trigger of triggers) {
const title = FEATURE_NAMES[trigger];
if (title && !seenTitles.has(title)) {
seenTitles.add(title);
featureNames.push(title.toLowerCase());
}
}
return featureNames.slice(0, 3); // Max 3 features
}
// Format feature names into a sentence (e.g., "secure data rooms, custom domains and team collaboration")
function formatFeatureList(names: string[]): string {
if (names.length === 0) return "";
if (names.length === 1) return names[0];
if (names.length === 2) return `${names[0]} and ${names[1]}`;
return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
}
interface UpgradeIntentEmailProps {
name: string | null | undefined;
triggers?: string[];
}
const UpgradeIntentEmail = ({ name, triggers = [] }: UpgradeIntentEmailProps) => {
const featureNames = getUniqueFeatureNames(triggers);
const hasFeatures = featureNames.length > 0;
const featureList = formatFeatureList(featureNames);
return (
<Html>
<Head />
<Tailwind>
<Body className="font-sans text-sm">
<Text>Hi{name && ` ${name}`},</Text>
<Text>
I noticed you&apos;ve been exploring our upgrade options.
{hasFeatures &&
` I am happy to share more about Papermark ${featureList}.`}
</Text>
<Text>
Is there anything holding you back or any questions I can help
answer?
</Text>
<Text>
<Link
href="https://app.papermark.com/settings/upgrade"
target="_blank"
className="text-blue-500 underline"
>
View upgrade options
</Link>
</Text>
<Text>Just reply to this email and I&apos;ll get back to you.</Text>
<Text>
Best,
<br />
Marc
</Text>
</Body>
</Tailwind>
</Html>
);
};
export default UpgradeIntentEmail;

Some files were not shown because too many files have changed in this diff Show More