Back to Blog
·14 min

Next.js API Routes: Production Backend Patterns and Best Practices

Next.js API routes can serve as a production backend for many applications, eliminating the need for a separate API server.

Route Handler Patterns

// app/api/projects/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { z } from 'zod'

const CreateProjectSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().optional(),
})

export async function GET(req: NextRequest) {
  const projects = await prisma.project.findMany({ orderBy: { createdAt: 'desc' } })
  return NextResponse.json(projects)
}

export async function POST(req: NextRequest) {
  const body = await req.json()
  const parsed = CreateProjectSchema.safeParse(body)
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
  }
  const project = await prisma.project.create({ data: parsed.data })
  return NextResponse.json(project, { status: 201 })
}

Error Handling Middleware

export function withErrorHandling(handler: Function) {
  return async (req: NextRequest, ctx: any) => {
    try {
      return await handler(req, ctx)
    } catch (error) {
      console.error('API Error:', error)
      if (error instanceof z.ZodError) {
        return NextResponse.json({ error: error.flatten() }, { status: 400 })
      }
      return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
    }
  }
}

Background Jobs

Use Inngest or QStash for background processing:

import { Inngest } from 'inngest'
const inngest = new Inngest({ id: 'my-app' })

export const processWebhook = inngest.createFunction(
  { id: 'process-webhook' },
  { event: 'webhook.received' },
  async ({ event, step }) => {
    await step.run('validate', () => validatePayload(event.data))
    await step.run('process', () => processPayload(event.data))
    await step.run('notify', () => sendNotification(event.data))
  }
)

The Bottom Line

The API Boilerplate from BreafIO provides complete API patterns with middleware, validation, and error handling. The SaaS Starter Kit uses these patterns for the billing backend. The Real-Time Chat uses API routes for messaging. The Admin Dashboard Pro includes admin API endpoints, and the Database Manager provides ORM patterns.

Ready to Build?

Get started with our production-ready starter kits and ship your project faster.

Browse Starter Kits