This project is designed as a learning resource for understanding API management, CORS configuration, and full-stack development using Next.js 16, TypeScript, Prisma ORM, and MySQL.
- β API Route Management in Next.js App Router
- β CORS Configuration and security best practices
- β CRUD Operations with proper RESTful conventions
- β TypeScript Integration for type-safe APIs
- β Database Management with Prisma ORM
- β Frontend-Backend Integration with React/TypeScript
- β Error Handling and validation
- β API Testing with Postman
next-api/
βββ app/
β βββ api/
β β βββ posts/
β β βββ route.ts # GET ALL, POST
β β βββ [id]/
β β βββ route.ts # GET, PUT, DELETE by ID
β βββ layout.tsx
β βββ page.tsx # Frontend React UI
β βββ globals.css
βββ types/
β βββ post.ts # TypeScript interfaces
β βββ api.ts # API-specific types
βββ prisma/
β βββ schema.prisma # Database schema
β βββ client/ # Prisma client
βββ middleware.ts # Global CORS configuration
βββ package.json
- RESTful API with proper HTTP methods
- CORS enabled for cross-origin requests
- TypeScript for type safety
- Prisma ORM for database operations
- MySQL database integration
- Error handling with appropriate status codes
- React with TypeScript for type-safe UI
- CRUD operations integration
- Real-time updates after mutations
- Form validation and error handling
- Responsive design
- Node.js 18+
- MySQL database
- Postman (for API testing)
git clone <your-repo>
cd next-api
npm install# Configure your database in .env
DATABASE_URL="mysql://username:password@localhost:3306/database_name"
# Generate Prisma client
npx prisma generate
# Push schema to database
npx prisma db push
# Or run migrations
npx prisma migrate dev --name initnpm run dev| Method | Endpoint | Description | Body |
|---|---|---|---|
GET |
/api/posts |
Get all posts | - |
POST |
/api/posts |
Create new post | {title, content, published} |
GET |
/api/posts/[id] |
Get post by ID | - |
PUT |
/api/posts/[id] |
Update post by ID | {title, content, published} |
DELETE |
/api/posts/[id] |
Delete post by ID | - |
OPTIONS |
/api/posts/* |
CORS preflight | - |
Create Post:
curl -X POST http://localhost:3000/api/posts \
-H "Content-Type: application/json" \
-d '{"title":"My Post","content":"Post content","published":true}'Get All Posts:
curl -X GET http://localhost:3000/api/postsCORS is a security feature that controls how web applications from one domain can interact with resources from another domain.
// In each route.ts file
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
export async function OPTIONS() {
return NextResponse.json({}, { headers: corsHeaders });
}// middleware.ts
export function middleware(request) {
const response = NextResponse.next();
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
return response;
}const allowedOrigins = [
'http://localhost:3000',
'https://yourdomain.com'
];
const getCorsHeaders = (request: Request) => {
const origin = request.headers.get('origin');
const isAllowed = allowedOrigins.includes(origin || '');
return {
'Access-Control-Allow-Origin': isAllowed ? origin : '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
};-
Import the Postman Collection
- Use the provided
Posts-CRUD-API.postman_collection.json - Set environment variables:
base_urlandcontent_type
- Use the provided
-
Test All Endpoints
- Follow the "Test All Scenarios" collection for complete flow
- Test error cases (validation, not found, etc.)
# Test CORS preflight
curl -X OPTIONS http://localhost:3000/api/posts \
-H "Origin: http://localhost:3000" \
-H "Access-Control-Request-Method: POST" \
-I
# Test API endpoints
curl -X GET http://localhost:3000/api/posts
curl -X POST http://localhost:3000/api/posts \
-H "Content-Type: application/json" \
-d '{"title":"Test","content":"Test content"}'model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}- Real-time CRUD operations
- Type-safe forms with React Hook Form
- Error handling and loading states
- Responsive UI design
- Inline editing capabilities
Solution: Ensure OPTIONS method is handled and proper headers are set
Solution: Implement OPTIONS handler with correct CORS headers
Solution: Use origin validation in CORS headers
Solution: Add Access-Control-Allow-Credentials: true header
# Development
DATABASE_URL="mysql://user:pass@localhost:3306/dev_db"
# Production
DATABASE_URL="mysql://user:pass@production-host:3306/prod_db"// Restrict to your domain in production
const allowedOrigins = process.env.NODE_ENV === 'production'
? ['https://yourdomain.com']
: ['http://localhost:3000', 'http://localhost:3001'];- Understand API route structure in Next.js
- Implement CRUD operations with proper HTTP methods
- Configure CORS for cross-origin requests
- Handle preflight OPTIONS requests
- Implement proper error handling and status codes
- Test API endpoints with Postman
- Integrate frontend with backend API
- Understand TypeScript benefits in API development
- Implement database operations with Prisma
- Deploy and configure for production
npm run dev # Start development server
npm run build # Build for production
npm run start # Start production server
npx prisma generate # Generate Prisma client
npx prisma db push # Push schema to database
npx prisma studio # Open Prisma database GUIThis is a learning project! Feel free to:
- Add new features
- Improve error handling
- Enhance the UI/UX
- Add authentication
- Implement pagination
- Add API documentation with Swagger
- Add Authentication - JWT or NextAuth.js
- Implement Pagination - Limit/offset or cursor-based
- Add API Rate Limiting - Prevent abuse
- Implement Caching - Redis for performance
- Add API Documentation - Swagger/OpenAPI
- Write Tests - Jest for API testing
- Containerize - Docker for deployment
- Add Monitoring - Logging and metrics
Happy Learning! π
This project demonstrates real-world API development patterns that you'll encounter in professional web development.