Next.js API Route - Contact Form Validation

mediumTypeScript

Lesson

API Route Handlers and Request Validation

API route handlers are functions that process HTTP requests and return appropriate responses. They're the backbone of server-side logic in web applications, handling everything from form submissions to data fetching. In modern web frameworks like Next.js, these handlers work with standard Web API objects like Request and Response.

A well-designed API route handler follows a clear pattern: validate the HTTP method, parse the request body, validate the data, and return structured responses with appropriate status codes. The key is defensive programming - assume the incoming data might be malformed, missing, or malicious.

Request validation is crucial for security and user experience. You need to check both the structure (are required fields present?) and the content (is the email format valid?). Always validate on the server side, even if you have client-side validation, because client-side checks can be bypassed.

HTTP status codes communicate what happened: 200 for success, 400 for client errors (like validation failures), 405 for unsupported methods, and 500 for server errors. Your response body should be consistent and informative, helping clients understand what went wrong and how to fix it.

The Request and Response objects from the Web API standard make this clean and portable. You can parse JSON with await request.json(), check the method with request.method, and create responses with new Response(body, options). This approach works across different JavaScript environments, not just browsers.

Example
1// Generic API handler pattern 2async function apiHandler(request: Request): Promise<Response> { 3 // 1. Check HTTP method 4 if (request.method !== 'POST') { 5 return new Response( 6 JSON.stringify({ error: 'Method not allowed' }), 7 { status: 405, headers: { 'Content-Type': 'application/json' } } 8 ); 9 } 10 11 // 2. Parse and validate request body 12 let data; 13 try { 14 data = await request.json(); 15 } catch { 16 return new Response( 17 JSON.stringify({ error: 'Invalid JSON' }), 18 { status: 400, headers: { 'Content-Type': 'application/json' } } 19 ); 20 } 21 22 // 3. Business logic validation 23 if (!data.username || data.username.length < 3) { 24 return new Response( 25 JSON.stringify({ error: 'Username must be at least 3 characters' }), 26 { status: 400, headers: { 'Content-Type': 'application/json' } } 27 ); 28 } 29 30 // 4. Success response 31 return new Response( 32 JSON.stringify({ success: true, user: data.username }), 33 { status: 200, headers: { 'Content-Type': 'application/json' } } 34 ); 35}
L3Always validate HTTP method first - fail fast for unsupported operations
L11Wrap JSON parsing in try-catch - malformed JSON should return 400, not crash
L20Validate business rules after parsing - check required fields and formats
L28Return consistent JSON structure with appropriate status codes

Key Takeaways

  • •API handlers should validate HTTP method, parse request safely, validate data, and return structured responses
  • •Use appropriate HTTP status codes: 200 for success, 400 for validation errors, 405 for wrong methods
  • •Always validate server-side regardless of client-side validation - never trust user input
Loading...