← Kembali ke Blog

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.

Your Name
5 min read
#Next.js#API#Backend#TypeScript
Membangun RESTful API yang Scalable dengan Next.js

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

![]jfj

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

  1. Consistent Response Format: Gunakan format response yang konsisten
  2. Proper HTTP Status Codes: 200, 201, 400, 401, 404, 500, etc.
  3. Versioning: /api/v1/users untuk versioning
  4. CORS Configuration: Set CORS headers dengan benar
  5. Environment Variables: Jangan hardcode secrets
  6. Logging: Implementasi logging yang proper
  7. 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.