API Routes
API Routes let you build a backend directly in your Next.js application. Instead of setting up a separate server, you can create API endpoints right alongside your frontend code.
Think of API routes as your application's back door. They let you handle database operations, authentication, and third-party API calls without exposing sensitive logic to the client.
Creating API Routes
To create an API route, you add a route.js file inside the app/api directory. The file path determines the API endpoint.
app/
โโโ api/
โโโ users/
โโโ route.js # Creates /api/users endpoint
Inside route.js, you export functions named after HTTP methods:
// app/api/users/route.js
import { NextResponse } from 'next/server';
export async function GET() {
const users = await getUsers();
return NextResponse.json(users);
}
export async function POST(request) {
const body = await request.json();
const newUser = await createUser(body);
return NextResponse.json(newUser, { status: 201 });
}
Handling Requests
API routes receive request objects that let you access headers, cookies, query parameters, and the request body.
export async function GET(request) {
const { searchParams } = new URL(request.url);
const page = searchParams.get('page') || 1;
const limit = searchParams.get('limit') || 10;
const users = await getUsers({ page, limit });
return NextResponse.json(users);
}
You can use these parameters to filter, paginate, or customize your API responses.
Dynamic API Routes
Just like page routes, API routes support dynamic segments. This is useful for endpoints that need to handle specific resources.
// app/api/users/[id]/route.js
export async function GET(request, { params }) {
const user = await getUser(params.id);
if (!user) {
return NextResponse.json(
{ error: 'User not found' },
{ status: 404 }
);
}
return NextResponse.json(user);
}
This creates an endpoint at /api/users/123 where 123 is the user ID.
Best Practices
When working with API routes, keep these practices in mind:
Validate input: Always validate and sanitize user input to prevent security issues.
Handle errors gracefully: Return appropriate error codes and messages when things go wrong.
Use proper HTTP methods: Use GET for fetching, POST for creating, PUT for updating, and DELETE for removing.
Keep routes organized: Structure your API routes logically, just like your page routes.
API routes make Next.js a full-stack framework, letting you build complete applications without leaving the project.