Building RESTful APIs with Next.js

John
10 min read

Next.js makes it incredibly easy to build full-stack applications with its built-in API routes. Let's explore how to create robust, type-safe REST APIs.

Why Next.js for APIs?

Next.js API routes offer several advantages:

  • Co-located with frontend - Keep your API and UI in one codebase
  • TypeScript support - Full type safety across your stack
  • Serverless by default - Deploy to Vercel with zero configuration
  • Built-in middleware - Easy request/response handling

Creating an API Route

Here's a simple API route in Next.js 14 with the App Router:

// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  const users = [
    { id: 1, name: 'John Doe', email: 'john@example.com' },
    { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
  ];

  return NextResponse.json(users);
}

export async function POST(request: NextRequest) {
  const body = await request.json();

  // Validate and process the data
  const newUser = {
    id: Date.now(),
    ...body
  };

  return NextResponse.json(newUser, { status: 201 });
}

Best Practices

1. Type Safety

Always define types for your API responses:

interface User {
  id: number;
  name: string;
  email: string;
}

interface ApiResponse<T> {
  data?: T;
  error?: string;
}

2. Error Handling

Implement consistent error handling:

try {
  // Your logic here
} catch (error) {
  return NextResponse.json(
    { error: 'Internal server error' },
    { status: 500 }
  );
}

3. Validation

Use libraries like Zod for runtime validation:

import { z } from 'zod';

const userSchema = z.object({
  name: z.string().min(2),
  email: z.string().email()
});

// In your POST handler
const validatedData = userSchema.parse(body);

Conclusion

Next.js API routes provide a powerful way to build full-stack applications with minimal configuration. Combined with TypeScript and proper error handling, you can create production-ready APIs quickly.