Membangun RESTful API yang Scalable dengan Next.js
Panduan lengkap membangun RESTful API yang scalable, secure, dan well-documented menggunakan Next.js App Router dan best practices modern.

Introduction
RESTful API adalah fondasi dari aplikasi modern. Dalam artikel ini, kita akan belajar cara membangun API yang scalable, secure, dan mudah di-maintain menggunakan Next.js.
Prerequisites
![]
Sebelum memulai, pastikan Anda familiar dengan:
- JavaScript/TypeScript dasar
- Konsep HTTP methods (GET, POST, PUT, DELETE)
- Async/await
- Next.js basics
Setup Project
Pertama, buat project Next.js baru:
npx create-next-app@latest my-api-project
cd my-api-project
API Route Structure
Next.js 14 App Router menggunakan struktur file yang intuitif untuk API routes:
app/
āāā api/
ā āāā users/
ā ā āāā route.ts // GET, POST /api/users
ā ā āāā [id]/
ā ā āāā route.ts // GET, PUT, DELETE /api/users/:id
ā āāā auth/
ā āāā [...nextauth]/
ā āāā route.ts
Creating Your First Endpoint
Mari buat endpoint sederhana untuk mengelola users:
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
// Implementasi logic untuk mendapatkan semua users
const users = await db.user.findMany()
return NextResponse.json({
success: true,
data: users
})
}
export async function POST(request: NextRequest) {
const body = await request.json()
// Validasi input
if (!body.email || !body.name) {
return NextResponse.json(
{ success: false, error: 'Missing required fields' },
{ status: 400 }
)
}
// Simpan ke database
const user = await db.user.create({ data: body })
return NextResponse.json(
{ success: true, data: user },
{ status: 201 }
)
}
Error Handling
Error handling yang baik sangat penting:
export async function GET(request: NextRequest) {
try {
const users = await db.user.findMany()
return NextResponse.json({ success: true, data: users })
} catch (error) {
console.error('Database error:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}
Validation dengan Zod
Gunakan Zod untuk type-safe validation:
import { z } from 'zod'
const userSchema = z.object({
email: z.string().email(),
name: z.string().min(2),
age: z.number().optional()
})
export async function POST(request: NextRequest) {
const body = await request.json()
// Validate
const result = userSchema.safeParse(body)
if (!result.success) {
return NextResponse.json(
{ success: false, errors: result.error.issues },
{ status: 400 }
)
}
const user = await db.user.create({ data: result.data })
return NextResponse.json({ success: true, data: user }, { status: 201 })
}
Authentication & Authorization
Proteksi endpoint dengan middleware:
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json(
{ success: false, error: 'Unauthorized' },
{ status: 401 }
)
}
await db.user.delete({ where: { id: params.id } })
return NextResponse.json({ success: true })
}
Rate Limiting
Implementasi rate limiting untuk mencegah abuse:
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s'),
})
export async function GET(request: NextRequest) {
const identifier = request.ip ?? 'anonymous'
const { success } = await ratelimit.limit(identifier)
if (!success) {
return NextResponse.json(
{ error: 'Too many requests' },
{ status: 429 }
)
}
// ... rest of the logic
}
API Documentation
Gunakan tools seperti Swagger/OpenAPI untuk dokumentasi:
/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* responses:
* 200:
* description: Success
*/
Best Practices
- Consistent Response Format: Gunakan format response yang konsisten
- Proper HTTP Status Codes: 200, 201, 400, 401, 404, 500, etc.
- Versioning:
/api/v1/users
untuk versioning - CORS Configuration: Set CORS headers dengan benar
- Environment Variables: Jangan hardcode secrets
- Logging: Implementasi logging yang proper
- Testing: Write tests untuk semua endpoints
Conclusion
Membangun RESTful API yang baik membutuhkan perencanaan dan perhatian terhadap detail. Dengan mengikuti best practices di atas, Anda dapat membuat API yang robust, secure, dan mudah di-maintain.
Resources
Happy coding! š
Terima kasih telah membaca! Jangan lupa untuk share artikel ini jika bermanfaat.