Generic middleware utilities and types for Next.js API routes.
npm install @raburski/next-api-middleware- Generic TypeScript types for API handlers and middleware
- Reusable middleware utilities
- Type-safe API route composition
Generic context type for API handlers that includes:
params: Route parameterssession: Optional session dataresource: Optional resource data- Additional custom properties
Generic handler function type for API endpoints.
Middleware function type that transforms a handler.
Generic middleware that ensures a resource exists and adds it to the context.
import { withResourceExists } from "@raburski/next-api-middleware"
import { db } from "@/server/db"
// Simple usage
const withBuildingExists = withResourceExists(
(id: string) => db.building.findUnique({ where: { id } }),
"Building"
)
// With custom error message
const withUserExists = withResourceExists(
(id: string) => db.user.findUnique({ where: { id } }),
"User",
{ errorMessage: "User not found" }
)
// With custom param name
const withCommentExists = withResourceExists(
(id: string) => db.comment.findUnique({ where: { id } }),
"Comment",
{ paramName: "commentId" }
)
// Usage in API route
export const GET = compose(
withBuildingExists,
withAuth
)(getBuilding)MIT