Generate REST API routes automatically from your Prisma schema for Next.js App Router.
- π Instant REST API - Generate CRUD endpoints from your Prisma models
- π Next.js App Router - Built for the modern Next.js app directory structure
- π§ Flexible Configuration - Customize paths, imports, and behavior
- π― Smart Defaults - Auto-detects project structure and follows conventions
- π Safe Regeneration - Multiple strategies for updating existing routes
- π TypeScript First - Fully typed route handlers with proper Next.js types
- π¬ Comment Directives - Control generation with special comments in your schema
npm install -D prisma-rest
# or
yarn add -D prisma-rest
# or
pnpm add -D prisma-rest
- Ensure you have a Prisma schema in your Next.js project:
// prisma/schema.prisma
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
- Generate your REST API routes:
npx prisma-rest generate
- Create your Prisma client instance:
// lib/prisma.ts (or src/lib/prisma.ts)
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
That's it! Your REST API is ready at:
GET /api/users
- List all users with paginationPOST /api/users
- Create a new userGET /api/users/[id]
- Get a specific userPUT /api/users/[id]
- Update a userDELETE /api/users/[id]
- Delete a user
For each Prisma model, the generator creates:
// GET /api/users - List with pagination
// Query params: ?page=1&limit=10
{
"items": [...],
"total": 100,
"page": 1,
"limit": 10,
"totalPages": 10
}
// POST /api/users - Create new resource
// Body: { "email": "user@example.com", "name": "John Doe" }
// GET /api/users/[id] - Get single resource
// PUT /api/users/[id] - Update resource
// DELETE /api/users/[id] - Delete resource
prisma-rest generate [options]
Options:
-s, --schema <path> Path to Prisma schema file (default: "./prisma/schema.prisma")
-o, --output <path> Output directory for generated routes
-b, --base-url <url> Base URL for API routes (default: "/api")
--api-prefix <prefix> Additional path prefix (e.g., "rest" for /api/rest)
-p, --prisma-import <path> Import path for Prisma client (default: "@/lib/prisma")
--include <models...> Include only specific models
--exclude <models...> Exclude specific models
--force Overwrite existing route files
--skip-existing Only generate routes for new models
--dry-run Preview what would be generated
-h, --help Display help
# Generate in a custom directory
prisma-rest generate --output ./src/app/api/v2
# Generate with a prefix
prisma-rest generate --api-prefix rest
# Creates routes at /api/rest/users, /api/rest/posts, etc.
# If your Prisma client is in a different location
prisma-rest generate --prisma-import "@/server/db"
# Only generate routes for specific models
prisma-rest generate --include User Post
# Generate all except certain models
prisma-rest generate --exclude Log Audit
# Preview changes without creating files
prisma-rest generate --dry-run
# Skip existing files (only add new models)
prisma-rest generate --skip-existing
# Force overwrite all files
prisma-rest generate --force
The generator automatically detects your project structure:
- β
Supports
/src
directory layouts - β
Detects App Router at
/app
or/src/app
- β
Understands Next.js path aliases (
@/
)
- TypeScript - Fully typed with Next.js route handler types
- Error Handling - Consistent error responses with appropriate status codes
- Pagination - Built-in pagination for list endpoints
- Async/Await - Modern async patterns throughout
- Prisma Best Practices - Efficient queries and proper error handling
- Next.js 13+ with App Router
- Prisma 4+
- TypeScript (recommended)
Control route generation using special comments in your Prisma schema:
Skip generation for specific models:
/// This model won't have REST routes generated
/// @rest-skip
model InternalLog {
id String @id @default(cuid())
message String
level String
createdAt DateTime @default(now())
}
This is useful for:
- Internal models that shouldn't be exposed via API
- Models that require custom handling
- Temporary exclusion during development
After generation, you can modify the routes to add:
- Authentication middleware
- Input validation
- Custom business logic
- Response transformations
The generated files include a header comment to track generation metadata.
Example of adding auth to generated routes:
import { withAuth } from '@/lib/auth';
// Wrap the generated handler
export const GET = withAuth(async (request: NextRequest) => {
// Generated code...
});
Ensure you've created the Prisma client instance at the correct location. The default import path is @/lib/prisma
, but you can customize it with the --prisma-import
flag.
By default, the generator won't overwrite existing files. Use:
--force
to overwrite--skip-existing
to only generate new models--dry-run
to preview changes
Contributions are welcome! Please feel free to submit a Pull Request.
MIT Β© [Your Name]
Made with β€οΈ for the Next.js + Prisma community