next-prisma-flow

Full-stack TypeScript state management from your Prisma schema

v0.2.2

Overview

A Prisma generator that scaffolds full-stack typed code for Next.js applications. Generate API routes, server actions, Jotai state management, React hooks, and smart form integration from your Prisma schema.

Type-Safe APIs

Generated API routes with complete TypeScript safety from database to frontend

Smart State Management

Jotai atoms with optimistic updates, error handling, and automatic cache invalidation

Form Integration

Specialized form hooks with validation, auto-save, and perfect type inference

Server Actions

Next.js 14+ server actions with relationship handling and business logic

Installation

npm install next-prisma-flow

Setup

prisma/schema.prisma
generator flow {
  provider = "next-prisma-flow"
  output   = "./generated/flow"
  models   = ["User", "Todo", "Category"]
  
  // Model-specific configuration
  todoSelect     = ["id", "title", "status", "userId"]
  todoOptimistic = "merge"
  todoPagination = "true"
}

model Todo {
  id          String   @id @default(cuid())
  title       String
  description String?
  status      Status   @default(PENDING)
  userId      String
  user        User     @relation(fields: [userId], references: [id])
}
app/layout.tsx
import { FlowProvider } from './generated/flow'

export default function RootLayout({ children }) {
  return (
    <FlowProvider
      config={{
        devTools: true,
        errorBoundary: true,
        autoRefresh: false,
      }}
    >
      {children}
    </FlowProvider>
  )
}

Generated Code

Run npx prisma generate to create a complete typed state management layer:

Modern API (v0.2.x)

components/TodoList.tsx
import { todo } from './generated/flow'

export function TodoList() {
  // One hook, everything you need
  const { 
    data: todoList,
    createTodo, 
    updateTodo, 
    deleteTodo,
    loading, 
    error 
  } = todo.hooks.useTodos()
  
  // Specialized form hooks
  const createForm = todo.hooks.useCreateTodoForm()
  
  return (
    <div>
      <form onSubmit={createForm.submit}>
        <input {...createForm.field('title')} />
        <button disabled={!createForm.isValid}>
          Add Todo
        </button>
      </form>
      
      {todoList.map(todo => (
        <TodoItem key={todo.id} todo={todo} />
      ))}
    </div>
  )
}

Advanced Patterns

hooks/useMyTodos.ts
import { atom } from 'jotai'
import { todo } from './generated/flow'

// Direct atom access for custom state
const { todosAtom } = todo.atoms

export const urgentTodosAtom = atom((get) => {
  const allTodos = get(todosAtom)
  return Object.values(allTodos)
    .filter(t => t.priority === 'HIGH')
})

// Programmatic actions
export async function bulkMarkComplete(ids) {
  await Promise.all(
    ids.map(id => 
      todo.actions.update(id, { 
        status: 'COMPLETED' 
      })
    )
  )
}

Generated Structure

For each model, the generator creates a complete typed interface:

generated/flow/todo/
├── actions.ts      # Server actions with business logic
├── atoms.ts        # Jotai atoms for state management
├── hooks.ts        # Enhanced React hooks
├── routes.ts       # Next.js API route handlers
├── types.ts        # TypeScript type definitions
├── smart-form.ts   # Form hook implementations
└── namespace.ts    # Organized exports

Namespace Exports

Modern API Structure
import { todo, category } from './generated/flow'

const todo = {
  hooks: {
    useTodos,           // Unified CRUD operations
    useTodo,            // Individual item management
    useCreateTodoForm,  // Specialized create form
    useUpdateTodoForm,  // Specialized update form
  },
  actions: {
    create, update, delete, getAll, getById,
    createMany, deleteMany,
  },
  atoms: {
    todosAtom, todosLoadingAtom, todosErrorAtom,
  },
  types: { Todo, TodoCreateInput, TodoUpdateInput },
  schemas: { create: TodoCreateInputSchema, update: TodoUpdateInputSchema }
}

FlowProvider Benefits

The new FlowProvider adds significant architectural value:

SSR/Hydration Safety

Prevents hydration mismatches and enables server-side data pre-population

Global Error Boundary

Centralized error handling for all Flow operations with custom handlers

Development Tools

Automatic React DevTools integration and debug utilities

Store Isolation

Clean store instances for testing and SSR environments

Configuration

Fine-tune generation with model-specific settings:

Schema Configuration
generator flow {
  provider = "next-prisma-flow"
  output   = "./generated/flow"
  models   = ["User", "Todo", "Category"]
  
  # Security & Performance
  userSelect     = ["id", "name", "email"]  # Field whitelist
  userOptimistic = "merge"                      # Update strategy
  
  todoSelect     = ["id", "title", "status", "userId"]
  todoOptimistic = "overwrite"
  todoPagination = "true"                     # Enable pagination
}

Available Options