Next.js course ยท Module 4: Databases and Data Fetching
Using API Routes in Next.js
In this lesson18
API Routes in Next.js allow creating server-side API endpoints directly within a Next.js application. They are extremely useful for creating custom API interfaces, handling external integrations, verification, and many other server-side scenarios.
What Are API Routes?
API Routes in Next.js are dedicated files that function as API endpoints accessible under specific URLs. After deploying a Next.js application, these endpoints are hosted as serverless functions.
In the App Router architecture (Next.js 13+), we use special route.ts files in the app directory structure to define API endpoints.
Creating an API Route in the App Router
To create an API endpoint, create a route.ts (or route.js) file in the appropriate subdirectory within the app structure. The file location defines the endpoint URL path.
Example of a basic API endpoint:
// app/api/hello/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ message: 'Hello, World!' });
}This simple API route is accessible at /api/hello and returns a JSON response containing the message "Hello, World!" on a GET request.
Handling Different HTTP Methods
API Routes in Next.js can handle all standard HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS. Simply define the appropriate functions in the route.ts file:
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
// Fetching the list of users
export async function GET() {
try {
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
createdAt: true,
},
});
return NextResponse.json(users);
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch users' },
{ status: 500 }
);
}
}
// Creating a new user
export async function POST(request: NextRequest) {
try {
const { name, email, password } = await request.json();
// Data validation
if (!name || !email || !password) {
return NextResponse.json(
{ error: 'Missing required fields' },
{ status: 400 }
);
}
// Check if the user already exists
const existingUser = await prisma.user.findUnique({
where: { email },
});
if (existingUser) {
return NextResponse.json(
{ error: 'A user with this email address already exists' },
{ status: 409 }
);
}
// Create a new user
const user = await prisma.user.create({
data: {
name,
email,
password, // In production, always hash passwords!
},
});
// Do not return the password in the response
const { password: _, ...userWithoutPassword } = user;
return NextResponse.json(userWithoutPassword, { status: 201 });
} catch (error) {
return NextResponse.json(
{ error: 'Failed to create user' },
{ status: 500 }
);
}
}Handling Dynamic URL Parameters
We can create dynamic API routes using bracket syntax in directory names, similar to dynamic pages:
// app/api/users/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
// Fetching user details
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
try {
const user = await prisma.user.findUnique({
where: { id },
select: {
id: true,
name: true,
email: true,
createdAt: true,
},
});
if (!user) {
return NextResponse.json(
{ error: 'User not found' },
{ status: 404 }
);
}
return NextResponse.json(user);
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch user' },
{ status: 500 }
);
}
}
// Updating user
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const { name, email } = await request.json();
try {
const updatedUser = await prisma.user.update({
where: { id },
data: {
name,
email,
},
select: {
id: true,
name: true,
email: true,
createdAt: true,
},
});
return NextResponse.json(updatedUser);
} catch (error) {
return NextResponse.json(
{ error: 'Failed to update user' },
{ status: 500 }
);
}
}
// Deleting user
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
try {
await prisma.user.delete({
where: { id },
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return NextResponse.json(
{ error: 'Failed to delete user' },
{ status: 500 }
);
}
}Handling Query Parameters
We can handle query parameters in the URL using the URL object:
// app/api/products/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(request: NextRequest) {
// Access query parameters
const { searchParams } = new URL(request.url);
// Get the parameters
const category = searchParams.get('category');
const limit = parseInt(searchParams.get('limit') || '10');
const page = parseInt(searchParams.get('page') || '1');
const sort = searchParams.get('sort') || 'createdAt_desc';
// Prepare filtering conditions
const where: any = {};
if (category) {
where.category = category;
}
// Prepare sorting
const [sortField, sortOrder] = sort.split('_');
const orderBy = {
[sortField]: sortOrder,
};
// Prepare pagination
const skip = (page - 1) * limit;
try {
// Fetch products with filters, sorting and pagination
const productsPromise = prisma.product.findMany({
where,
orderBy,
skip,
take: limit,
});
// Get the total number of products matching the filter criteria
const totalPromise = prisma.product.count({
where,
});
// Execute both queries in parallel
const [products, total] = await Promise.all([productsPromise, totalPromise]);
// Calculate the total number of pages
const totalPages = Math.ceil(total / limit);
// Prepare pagination information
const pagination = {
total,
page,
limit,
totalPages,
hasNextPage: page < totalPages,
hasPrevPage: page > 1,
};
return NextResponse.json({
products,
pagination,
});
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch products' },
{ status: 500 }
);
}
}File Handling in API Routes
We can handle file uploads in API Routes using the form interface:
// app/api/upload/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
export async function POST(request: NextRequest) {
try {
const formData = await request.formData();
const file = formData.get('file') as File;
if (!file) {
return NextResponse.json(
{ error: 'File not found' },
{ status: 400 }
);
}
// Check the file type
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!allowedTypes.includes(file.type)) {
return NextResponse.json(
{ error: 'Disallowed file type. Allowed types: ' + allowedTypes.join(', ') },
{ status: 400 }
);
}
// File size limit (5MB)
const maxSize = 5 * 1024 * 1024;
if (file.size > maxSize) {
return NextResponse.json(
{ error: 'File is too large. Maximum size: 5MB' },
{ status: 400 }
);
}
// Generate a unique file name
const fileExtension = file.name.split('.').pop();
const fileName = `${uuidv4()}.${fileExtension}`;
// File save path (in a real application we would probably use a service like S3)
const uploadDir = join(process.cwd(), 'public', 'uploads');
const filePath = join(uploadDir, fileName);
// Convert the file to a buffer
const buffer = Buffer.from(await file.arrayBuffer());
// Save the file
await writeFile(filePath, buffer);
// Return the file path
const fileUrl = `/uploads/${fileName}`;
return NextResponse.json({ fileUrl }, { status: 201 });
} catch (error) {
return NextResponse.json(
{ error: 'Failed to upload file' },
{ status: 500 }
);
}
}Authentication and Authorization in API Routes
We can implement middleware for API request authentication:
// middleware.ts (in the project root directory)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyJwtToken } from './lib/auth';
// Middleware function executed before requests
export async function middleware(request: NextRequest) {
// Check if the path is protected
const isApiRoute = request.nextUrl.pathname.startsWith('/api/');
const isPublicRoute = [
'/api/auth/login',
'/api/auth/register',
].includes(request.nextUrl.pathname);
// If this is not an API route or is public, allow access
if (!isApiRoute || isPublicRoute) {
return NextResponse.next();
}
// Get the token from the Authorization header
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json(
{ error: 'No authorization' },
{ status: 401 }
);
}
// Extract the token
const token = authHeader.split(' ')[1];
try {
// Verify the token
const decoded = await verifyJwtToken(token);
// Add user data to request headers so they are available in the API Route
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-user-id', decoded.userId);
// Continue with the added headers
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
} catch (error) {
return NextResponse.json(
{ error: 'Invalid authorization token' },
{ status: 401 }
);
}
}
// Specify for which paths the middleware should run
export const config = {
matcher: ['/api/:path*'],
};And now an API Route for login that generates a JWT token:
// app/api/auth/login/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { comparePasswords, generateJwtToken } from '@/lib/auth';
export async function POST(request: NextRequest) {
try {
const { email, password } = await request.json();
// Check if email and password were provided
if (!email || !password) {
return NextResponse.json(
{ error: 'Email and password are required' },
{ status: 400 }
);
}
// Find the user by email
const user = await prisma.user.findUnique({
where: { email },
});
// Check if the user exists
if (!user) {
return NextResponse.json(
{ error: 'Invalid email or password' },
{ status: 401 }
);
}
// Check if the password is correct
const isPasswordValid = await comparePasswords(password, user.password);
if (!isPasswordValid) {
return NextResponse.json(
{ error: 'Invalid email or password' },
{ status: 401 }
);
}
// Generate the JWT token
const token = await generateJwtToken({ userId: user.id });
// Do not return the password in the response
const { password: _, ...userWithoutPassword } = user;
return NextResponse.json({
user: userWithoutPassword,
token,
});
} catch (error) {
return NextResponse.json(
{ error: 'Login error' },
{ status: 500 }
);
}
}Error Handling and HTTP Status Codes
It's good practice to properly handle errors and use appropriate HTTP status codes in APIs:
// app/api/example/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
try {
// Business logic...
// Success: status 200 OK
return NextResponse.json({ data: [...] });
} catch (error) {
console.error('API error:', error);
// Determine the appropriate status code based on the error type
if (error instanceof NotFoundError) {
return NextResponse.json(
{ error: 'Resource not found' },
{ status: 404 }
);
} else if (error instanceof ValidationError) {
return NextResponse.json(
{ error: 'Data validation error', details: error.details },
{ status: 400 }
);
} else if (error instanceof AuthorizationError) {
return NextResponse.json(
{ error: 'No permission to access this resource' },
{ status: 403 }
);
} else {
// General server error: status 500 Internal Server Error
return NextResponse.json(
{ error: 'An internal server error occurred' },
{ status: 500 }
);
}
}
}CORS Handling (Cross-Origin Resource Sharing)
If the API needs to be accessible from other domains, CORS configuration is necessary:
// app/api/cors-example/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// Get the data
const data = { message: 'This is an API with CORS support' };
// Create response
const response = NextResponse.json(data);
// Add CORS headers
response.headers.set('Access-Control-Allow-Origin', '*'); // Or a specific domain
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
return response;
}
// Handling OPTIONS requests (preflight requests)
export async function OPTIONS(request: NextRequest) {
const response = new NextResponse(null, { status: 204 });
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
response.headers.set('Access-Control-Max-Age', '86400'); // 24 hours
return response;
}Alternatively, we can configure CORS globally using middleware:
// middleware.ts (fragment)
export function middleware(request: NextRequest) {
// ...existing middleware code
// CORS for all API Routes
if (request.nextUrl.pathname.startsWith('/api/')) {
const response = NextResponse.next();
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// For OPTIONS requests return immediately
if (request.method === 'OPTIONS') {
return new NextResponse(null, {
status: 204,
headers: response.headers,
});
}
return response;
}
return NextResponse.next();
}Rate Limiting
To protect the API from abuse, we can implement rate limiting:
// lib/rate-limit.ts
type RateLimitOptions = {
windowMs: number; // Time window in milliseconds
maxRequests: number; // Maximum number of requests in the time window
};
const defaultOptions: RateLimitOptions = {
windowMs: 60 * 1000, // 1 minute
maxRequests: 100, // 100 requests per minute
};
// Store request records in memory (in production use Redis or similar service)
const requestRecords = new Map<string, { count: number, resetTime: number }>();
export function rateLimit(ip: string, options: Partial<RateLimitOptions> = {}) {
const { windowMs, maxRequests } = { ...defaultOptions, ...options };
const now = Date.now();
const record = requestRecords.get(ip) || { count: 0, resetTime: now + windowMs };
// Reset counter if reset time has passed
if (now > record.resetTime) {
record.count = 1;
record.resetTime = now + windowMs;
} else {
record.count += 1;
}
requestRecords.set(ip, record);
// Check if limit exceeded
if (record.count > maxRequests) {
return {
limited: true,
resetTime: record.resetTime,
remaining: 0,
};
}
return {
limited: false,
resetTime: record.resetTime,
remaining: maxRequests - record.count,
};
}Usage in an API Route:
// app/api/protected/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { rateLimit } from '@/lib/rate-limit';
export async function GET(request: NextRequest) {
// Get the client IP
const ip = request.ip || 'anonymous';
// Apply rate limiting
const rateLimitResult = rateLimit(ip, {
windowMs: 60 * 1000, // 1 minute
maxRequests: 10, // 10 requests per minute
});
// If limit exceeded, return error 429 Too Many Requests
if (rateLimitResult.limited) {
const response = NextResponse.json(
{ error: 'Too many requests. Please try again later.' },
{ status: 429 }
);
// Add headers informing about the limit
response.headers.set('Retry-After', Math.ceil((rateLimitResult.resetTime - Date.now()) / 1000).toString());
response.headers.set('X-RateLimit-Limit', '10');
response.headers.set('X-RateLimit-Remaining', '0');
response.headers.set('X-RateLimit-Reset', Math.ceil(rateLimitResult.resetTime / 1000).toString());
return response;
}
// Standard response with added rate limit headers
const response = NextResponse.json({ data: 'API Content' });
response.headers.set('X-RateLimit-Limit', '10');
response.headers.set('X-RateLimit-Remaining', rateLimitResult.remaining.toString());
response.headers.set('X-RateLimit-Reset', Math.ceil(rateLimitResult.resetTime / 1000).toString());
return response;
}Using API Routes in Client Components
Here's how we can use API Routes in a client component:
// components/UserProfile.tsx
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
interface User {
id: string;
name: string;
email: string;
}
export default function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
useEffect(() => {
async function fetchUser() {
try {
setLoading(true);
// Get token from localStorage (assuming it was saved there after login)
const token = localStorage.getItem('token');
const response = await fetch(`/api/users/${userId}`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (!response.ok) {
// HTTP error handling
if (response.status === 401) {
// Unauthorized - redirect to login page
router.push('/login');
return;
}
const errorData = await response.json();
throw new Error(errorData.error || 'An error occurred while fetching user data');
}
const userData = await response.json();
setUser(userData);
} catch (error) {
setError(error instanceof Error ? error.message : 'An unknown error occurred');
} finally {
setLoading(false);
}
}
fetchUser();
}, [userId, router]);
// Loading state handling
if (loading) {
return <div className="p-4">Loading user profile...</div>;
}
// Error handling
if (error) {
return <div className="p-4 text-red-500">Error: {error}</div>;
}
// User not found handling
if (!user) {
return <div className="p-4">User not found.</div>;
}
// Rendering user profile
return (
<div className="p-4">
<h1 className="text-2xl font-bold mb-4">User Profile</h1>
<div className="bg-white p-6 rounded shadow">
<div className="mb-4">
<strong className="text-gray-700">Full name:</strong>
<p className="text-gray-900">{user.name}</p>
</div>
<div className="mb-4">
<strong className="text-gray-700">Email:</strong>
<p className="text-gray-900">{user.email}</p>
</div>
</div>
</div>
);
}Form Data Handling with React Hook Form
Here's an example of using React Hook Form to send form data to an API Route:
// components/UserForm.tsx
'use client';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// Form data validation schema
const userSchema = z.object({
name: z.string().min(2, 'Full name must be at least 2 characters'),
email: z.string().email('Please provide a valid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
confirmPassword: z.string(),
}).refine(data => data.password === data.confirmPassword, {
message: 'Passwords must match',
path: ['confirmPassword'],
});
type UserFormData = z.infer<typeof userSchema>;
export default function UserForm() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [serverError, setServerError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm<UserFormData>({
resolver: zodResolver(userSchema),
});
const onSubmit = async (data: UserFormData) => {
try {
setIsSubmitting(true);
setServerError(null);
setSuccess(false);
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: data.name,
email: data.email,
password: data.password,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'An error occurred during registration');
}
// Success
setSuccess(true);
reset(); // Reset the form
} catch (error) {
setServerError(error instanceof Error ? error.message : 'An unknown error occurred');
} finally {
setIsSubmitting(false);
}
};
return (
<div className="max-w-md mx-auto mt-8">
<h1 className="text-2xl font-bold mb-4">User Registration</h1>
{/* Success message */}
{success && (
<div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
Registration successful! You can now log in.
</div>
)}
{/* Server error message */}
{serverError && (
<div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
{serverError}
</div>
)}
<form onSubmit={handleSubmit(onSubmit)} className="bg-white p-6 rounded shadow">
<div className="mb-4">
<label htmlFor="name" className="block text-gray-700 mb-2">
Full name
</label>
<input
type="text"
id="name"
{...register('name')}
className="w-full px-3 py-2 border rounded"
disabled={isSubmitting}
/>
{errors.name && (
<p className="text-red-500 text-sm mt-1">{errors.name.message}</p>
)}
</div>
<div className="mb-4">
<label htmlFor="email" className="block text-gray-700 mb-2">
Email
</label>
<input
type="email"
id="email"
{...register('email')}
className="w-full px-3 py-2 border rounded"
disabled={isSubmitting}
/>
{errors.email && (
<p className="text-red-500 text-sm mt-1">{errors.email.message}</p>
)}
</div>
<div className="mb-4">
<label htmlFor="password" className="block text-gray-700 mb-2">
Password
</label>
<input
type="password"
id="password"
{...register('password')}
className="w-full px-3 py-2 border rounded"
disabled={isSubmitting}
/>
{errors.password && (
<p className="text-red-500 text-sm mt-1">{errors.password.message}</p>
)}
</div>
<div className="mb-6">
<label htmlFor="confirmPassword" className="block text-gray-700 mb-2">
Confirm password
</label>
<input
type="password"
id="confirmPassword"
{...register('confirmPassword')}
className="w-full px-3 py-2 border rounded"
disabled={isSubmitting}
/>
{errors.confirmPassword && (
<p className="text-red-500 text-sm mt-1">{errors.confirmPassword.message}</p>
)}
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 disabled:opacity-50"
>
{isSubmitting ? 'Registering...' : 'Register'}
</button>
</form>
</div>
);
}Testing API Routes
For testing API Routes in Next.js, we can use libraries such as jest, supertest, or React Testing Library:
// __tests__/api/users.test.ts
import { NextRequest } from 'next/server';
import { GET } from '@/app/api/users/route';
// Mock the prisma module
jest.mock('@/lib/prisma', () => ({
prisma: {
user: {
findMany: jest.fn(),
},
},
}));
import { prisma } from '@/lib/prisma';
describe('Users API', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return a list of users', async () => {
// Mock the database response
const mockUsers = [
{ id: '1', name: 'Jan Kowalski', email: 'jan@example.com', createdAt: new Date() },
{ id: '2', name: 'Anna Nowak', email: 'anna@example.com', createdAt: new Date() },
];
(prisma.user.findMany as jest.Mock).mockResolvedValue(mockUsers);
// Create a fake request
const request = new NextRequest('http://localhost:3000/api/users');
// Call the API function
const response = await GET(request);
// Verify the response is correct
expect(response.status).toBe(200);
const responseData = await response.json();
expect(responseData).toEqual(mockUsers);
// Verify that prisma was called correctly
expect(prisma.user.findMany).toHaveBeenCalledTimes(1);
});
it('should handle errors properly', async () => {
// Mock a database error
(prisma.user.findMany as jest.Mock).mockRejectedValue(new Error('Database error'));
// Create a fake request
const request = new NextRequest('http://localhost:3000/api/users');
// Call the API function
const response = await GET(request);
// Verify the response contains an error
expect(response.status).toBe(500);
const responseData = await response.json();
expect(responseData).toEqual({ error: 'Failed to fetch users' });
});
});Integration with External APIs
API Routes are ideal for creating proxies for external APIs, allowing you to hide API keys and add additional logic:
// app/api/weather/route.ts
import { NextRequest, NextResponse } from 'next/server';
// Get the API key from environment variables
const WEATHER_API_KEY = process.env.WEATHER_API_KEY;
const WEATHER_API_URL = 'https://api.weatherapi.com/v1/current.json';
export async function GET(request: NextRequest) {
try {
// Get query parameters
const { searchParams } = new URL(request.url);
const city = searchParams.get('city');
if (!city) {
return NextResponse.json(
{ error: 'The "city" parameter is required' },
{ status: 400 }
);
}
// Build the URL to the external API
const apiUrl = `${WEATHER_API_URL}?key=${WEATHER_API_KEY}&q=${encodeURIComponent(city)}&aqi=no`;
// Fetch data from the external API
const response = await fetch(apiUrl);
if (!response.ok) {
// Handle errors from the external API
const errorData = await response.json();
// Map the error code to an appropriate response
if (response.status === 404) {
return NextResponse.json(
{ error: 'No data found for the specified city' },
{ status: 404 }
);
} else {
throw new Error(errorData.error?.message || 'External API error');
}
}
// Parse the weather data
const weatherData = await response.json();
// Transform the data into the format you want to return (optional)
const processedData = {
city: weatherData.location.name,
country: weatherData.location.country,
temperature: weatherData.current.temp_c,
condition: weatherData.current.condition.text,
icon: weatherData.current.condition.icon,
humidity: weatherData.current.humidity,
windSpeed: weatherData.current.wind_kph,
updatedAt: weatherData.current.last_updated,
};
// Add cache header
const responseHeaders = new Headers();
responseHeaders.set('Cache-Control', 'public, max-age=300'); // Cache for 5 minutes
return NextResponse.json(processedData, {
status: 200,
headers: responseHeaders,
});
} catch (error) {
console.error('Weather API error:', error);
return NextResponse.json(
{ error: 'Failed to fetch weather data' },
{ status: 500 }
);
}
}Payment Handling with Stripe
API Routes are ideal for integrating with payment gateways such as Stripe:
// app/api/checkout/route.ts
import { NextRequest, NextResponse } from 'next/server';
import Stripe from 'stripe';
import { prisma } from '@/lib/prisma';
// Initialize Stripe
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2023-10-16',
});
export async function POST(request: NextRequest) {
try {
const { productId, quantity = 1 } = await request.json();
// Data validation
if (!productId) {
return NextResponse.json(
{ error: 'Missing product identifier' },
{ status: 400 }
);
}
// Fetch the product from the database
const product = await prisma.product.findUnique({
where: { id: productId },
});
if (!product) {
return NextResponse.json(
{ error: 'Product not found' },
{ status: 404 }
);
}
// Create a Stripe Checkout session
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: product.name,
description: product.description || undefined,
images: product.imageUrl ? [product.imageUrl] : undefined,
},
unit_amount: Math.round(product.price * 100), // Convert to "cents"
},
quantity,
},
],
mode: 'payment',
success_url: `${request.headers.get('origin')}/order/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${request.headers.get('origin')}/order/cancelled`,
});
// Save order information in the database
await prisma.order.create({
data: {
stripeSessionId: session.id,
amount: product.price * quantity,
status: 'pending',
productId: product.id,
quantity,
},
});
// Return the Stripe session ID
return NextResponse.json({ sessionId: session.id });
} catch (error) {
console.error('Stripe checkout error:', error);
return NextResponse.json(
{ error: 'Failed to create payment session' },
{ status: 500 }
);
}
}Webhook for Handling Stripe Events
To handle events from external systems such as Stripe, we can create a webhook endpoint:
// app/api/webhooks/stripe/route.ts
import { NextRequest, NextResponse } from 'next/server';
import Stripe from 'stripe';
import { prisma } from '@/lib/prisma';
// Initialize Stripe
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2023-10-16',
});
// Webhook secret for signature verification
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;
export async function POST(request: NextRequest) {
try {
// Get the raw request data
const payload = await request.text();
// Get the Stripe signature header
const signature = request.headers.get('stripe-signature');
if (!signature) {
return NextResponse.json(
{ error: 'Missing Stripe signature header' },
{ status: 400 }
);
}
// Verify the event
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(payload, signature, webhookSecret);
} catch (err) {
console.error('Webhook signature verification error:', err);
return NextResponse.json(
{ error: 'Invalid webhook signature' },
{ status: 400 }
);
}
// Handle different event types
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session;
// Update the order status in the database
await prisma.order.update({
where: { stripeSessionId: session.id },
data: {
status: 'completed',
paidAt: new Date(),
customerEmail: session.customer_details?.email,
},
});
// Perform additional actions after successful payment
// e.g. send email confirmation, update product inventory, etc.
break;
}
case 'checkout.session.expired': {
const session = event.data.object as Stripe.Checkout.Session;
// Update the order status as expired
await prisma.order.update({
where: { stripeSessionId: session.id },
data: { status: 'expired' },
});
break;
}
// You can add more cases for other Stripe event types
}
// Return a 200 OK response to acknowledge receipt
return new NextResponse(null, { status: 200 });
} catch (error) {
console.error('Stripe webhook processing error:', error);
return NextResponse.json(
{ error: 'An internal server error occurred' },
{ status: 500 }
);
}
}
// Disable JSON body parsing for this endpoint
export const config = {
api: {
bodyParser: false,
},
};API Routes vs Server Components
It's worth noting that with the introduction of Server Components in Next.js 13+, the need for API Routes has decreased in some cases. We can perform many operations such as direct database access and data fetching in Server Components.
However, API Routes are still essential in the following cases:
- Handling external requests - When you need an endpoint to which requests can be sent from external systems (e.g., webhooks)
- Authentication and authorization - When you need a dedicated endpoint for login, registration, etc.
- Data mutation operations - Although we can use Server Actions, API Routes offer a more traditional way to implement mutation operations
- Integration with external APIs - When you want to hide API keys or add additional logic before redirecting to an external API
- Payment handling - Implementing integration with payment gateways such as Stripe
- File uploads - Advanced file upload handling
Summary
API Routes in Next.js offer powerful capabilities for creating custom API interfaces directly within the application. They are ideal for:
- Creating a backend - API functions can serve as a lightweight backend for Next.js applications
- Protecting sensitive data - They allow hiding API keys and other confidential information from the client
- Integration with external services - They enable easy integration with databases, payment systems, and other external services
- Handling data modification operations - They provide a secure way to perform CRUD operations
- Handling webhooks - They allow receiving notifications from external systems
Thanks to API Routes, Next.js offers a complete full-stack solution that allows building both frontend and backend of the application within a single project, significantly simplifying the development and deployment process.
In the next module, we will discuss rendering and caching strategies in Next.js 16, including Partial Prerendering (PPR), which further expand the framework's capabilities.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// API Routes (Route Handlers) in the Next.js App Router
// app/api/[...]/route.ts - GET, POST, PUT, DELETE
const endpoints = [
{
method: 'GET',
path: '/api/citizens',
color: '#50fa7b',
code: `// app/api/citizens/route.ts
import { prisma } from '@/lib/prisma';
import { NextRequest } from 'next/server';
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const page = Number(searchParams.get('page') || '1');
const limit = 10;
const citizens = await prisma.citizen.findMany({
skip: (page - 1) * limit,
take: limit,
include: { district: true },
});
return Response.json({ data: citizens, page });
}`,
response: '{ "data": [{ "id": "cit_1", "name": "Kira Neon" }], "page": 1 }',
},
{
method: 'POST',
path: '/api/citizens',
color: '#8be9fd',
code: `// app/api/citizens/route.ts
import { prisma } from '@/lib/prisma';
export async function POST(request: Request) {
const body = await request.json();
// Data validation
if (!body.name || !body.districtId) {
return Response.json(
{ error: 'Required fields: name, districtId' },
{ status: 400 }
);
}
const citizen = await prisma.citizen.create({
data: {
name: body.name,
districtId: body.districtId,
},
});
return Response.json(citizen, { status: 201 });
}`,
response: '{ "id": "cit_new", "name": "Neo Matrix", "districtId": "d_1" }',
},
{
method: 'PUT',
path: '/api/citizens/[id]',
color: '#ffb86c',
code: `// app/api/citizens/[id]/route.ts
import { prisma } from '@/lib/prisma';
export async function PUT(
request: Request,
{ params }: { params: { id: string } }
) {
const body = await request.json();
const citizen = await prisma.citizen.update({
where: { id: params.id },
data: body,
});
return Response.json(citizen);
}`,
response: '{ "id": "cit_1", "name": "Kira Neon Updated" }',
},
{
method: 'DELETE',
path: '/api/citizens/[id]',
color: '#ff5555',
code: `// app/api/citizens/[id]/route.ts
import { prisma } from '@/lib/prisma';
export async function DELETE(
_request: Request,
{ params }: { params: { id: string } }
) {
await prisma.citizen.delete({
where: { id: params.id },
});
return new Response(null, { status: 204 });
}`,
response: '204 No Content',
},
];
export default function ApiRoutesDemo() {
const [active, setActive] = useState(0);
const ep = endpoints[active];
return (
<div style={{
background: '#0f0f23',
minHeight: '100vh',
padding: '24px',
color: '#e0e0e0',
fontFamily: 'monospace'
}}>
<h1 style={{ color: '#64ffda' }}>
API Routes (Route Handlers)
</h1>
<p style={{ color: '#8892b0', marginBottom: '20px' }}>
app/api/.../route.ts - CRUD for Metropolis Quantum
</p>
{/* Method buttons */}
<div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
{endpoints.map((e, i) => (
<button
key={i}
onClick={() => setActive(i)}
style={{
padding: '8px 16px',
background: active === i ? e.color : '#1a1a2e',
color: active === i ? '#0f0f23' : e.color,
border: `1px solid ${e.color}`,
borderRadius: '4px',
cursor: 'pointer',
fontFamily: 'monospace',
fontWeight: 'bold',
}}
>
{e.method}
</button>
))}
</div>
{/* Path */}
<div style={{
padding: '8px 12px',
background: '#1a1a2e',
borderRadius: '4px',
marginBottom: '16px',
border: '1px solid #16213e',
display: 'flex',
alignItems: 'center',
gap: '8px',
}}>
<span style={{
background: ep.color,
color: '#0f0f23',
padding: '2px 8px',
borderRadius: '3px',
fontWeight: 'bold',
fontSize: '12px',
}}>
{ep.method}
</span>
<code style={{ color: '#c9d1d9' }}>{ep.path}</code>
</div>
{/* Code */}
<div style={{
background: '#1a1a2e',
borderRadius: '8px',
padding: '16px',
marginBottom: '16px',
border: `1px solid ${ep.color}44`,
}}>
<h3 style={{ color: ep.color, marginBottom: '8px' }}>
Implementation
</h3>
<pre style={{
background: '#0d1117',
padding: '12px',
borderRadius: '4px',
fontSize: '12px',
overflowX: 'auto',
color: '#c9d1d9',
}}>
{ep.code}
</pre>
</div>
{/* Response */}
<div style={{
background: '#1a1a2e',
borderRadius: '8px',
padding: '16px',
border: '1px solid #16213e',
}}>
<h3 style={{ color: '#ff79c6', marginBottom: '8px' }}>
Response
</h3>
<pre style={{
background: '#0d1117',
padding: '12px',
borderRadius: '4px',
fontSize: '12px',
color: '#50fa7b',
}}>
{ep.response}
</pre>
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which file do you create in the App Router (Next.js 13+) to define an API endpoint at a given URL?
2. Which HTTP status code do you return from NextResponse.json after successfully creating a new resource (e.g. a user)?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the route.ts file: add an export async function GET that returns data via NextResponse.json, and a POST that reads the body via request.json() and returns status 201.
- Horizontal ordering
Arrange the import statement for the response object in a route.ts file (left to right):