การตรวจสอบคำขอและความปลอดภัย
นำการตรวจสอบข้อมูลนำเข้าไปใช้ และรักษาความปลอดภัยให้เส้นทาง API จากช่องโหว่ทั่วไป
การตรวจสอบคำขอและความปลอดภัย เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack Web Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Validate & Secure Requests?
When building web applications, especially with API routes, you'll receive data from users. This data often comes from forms, client-side requests, or other external sources.
It's crucial to ensure this incoming data is valid and safe. Without proper validation and security measures, your application can be vulnerable to errors, data corruption, or even malicious attacks.
What is Input Validation?
Input validation is the process of ensuring that data provided by a user (or another system) meets specific criteria before your application processes it. This involves checking:
- Data Type: Is it a string, number, boolean?
- Format: Does an email address look like an email? Is a date in the correct format?
- Length: Is a username between 3 and 20 characters?
- Range: Is an age a positive number?
- Content: Does it contain only allowed characters?
Client vs. Server-Side Validation
You might perform validation on the client-side (in the browser) for a better user experience, providing instant feedback.
However, server-side validation is non-negotiable for security and data integrity. Client-side validation can be bypassed by malicious users. Always validate data on your server before processing it or storing it in a database.
Introducing Zod for Validation
Zod is a popular TypeScript-first schema declaration and validation library. It allows you to define the expected shape and types of your data, then validate incoming data against that schema.
Key benefits:
- Type Safety: Infers types from your schemas.
- Robust: Handles complex validation rules.
- Developer Friendly: Easy to read and write.
Basic Zod Schema Example
Let's see how to define a simple Zod schema for user input. This example checks for a valid username, email, and age.
Try running it with both valid and invalid data.
const { z } = require('zod');
const UserSchema = z.object({
username: z.string().min(3, "Username too short"),
email: z.string().email("Invalid email format"),
age: z.number().int().positive("Age must be positive"),
});
const validData = {
username: "coddyuser",
email: "coddy@example.com",
age: 30,
};
const invalidData = {
username: "co",
email: "bad-email",
age: -10,
};
console.log("--- Valid Data Test ---");
try {
const parsed = UserSchema.parse(validData);
console.log("Valid data:", parsed);
} catch (error) {
console.error("Validation failed:", error.errors);
}
console.log("\n--- Invalid Data Test ---");
try {
const parsed = UserSchema.parse(invalidData);
console.log("Valid data:", parsed);
} catch (error) {
console.error("Validation failed:", error.errors);
}Integrating Zod in Route Handlers
In Next.js, you'll use Zod within your API Route Handlers (e.g., app/api/users/route.ts) to validate incoming request bodies. This ensures that any data sent to your API meets your expectations before further processing.
We typically use a try-catch block to handle potential validation errors.
import { NextResponse } from 'next/server';
import { z } from 'zod';
// Define the schema for creating a new post
const CreatePostSchema = z.object({
title: z.string().min(5, 'Title must be at least 5 characters.'),
content: z.string().min(10, 'Content must be at least 10 characters.'),
authorId: z.string().uuid('Author ID must be a valid UUID.'),
});
export async function POST(request: Request) {
try {
const body = await request.json();
// Validate the request body using Zod
const validatedData = CreatePostSchema.parse(body);
// If validation passes, proceed with your logic
// e.g., save to database, perform other operations
console.log('Received valid post data:', validatedData);
return NextResponse.json(
{ message: 'Post created successfully', data: validatedData },
{ status: 201 }
);
} catch (error) {
// We'll handle errors in the next scene!
return NextResponse.json(
{ message: 'An unexpected error occurred.' },
{ status: 500 }
);
}
}Handling Validation Errors Gracefully
When Zod validation fails, it throws a ZodError. It's important to catch this specific error and return a clear, informative response to the client, typically with an HTTP 400 Bad Request status code.
This helps client applications understand what went wrong and display appropriate messages to users.
import { NextResponse } from 'next/server';
import { z } from 'zod';
const CreatePostSchema = z.object({
title: z.string().min(5, 'Title must be at least 5 characters.'),
content: z.string().min(10, 'Content must be at least 10 characters.'),
authorId: z.string().uuid('Author ID must be a valid UUID.'),
});
export async function POST(request: Request) {
try {
const body = await request.json();
const validatedData = CreatePostSchema.parse(body);
console.log('Received valid post data:', validatedData);
return NextResponse.json(
{ message: 'Post created successfully', data: validatedData },
{ status: 201 }
);
} catch (error) {
// Catch ZodError specifically for validation failures
if (error instanceof z.ZodError) {
console.error('Validation failed:', error.errors);
return NextResponse.json(
{ message: 'Validation failed', errors: error.errors },
{ status: 400 }
);
}
// Handle other unexpected errors
console.error('Server error:', error);
return NextResponse.json(
{ message: 'Internal server error' },
{ status: 500 }
);
}
}Beyond Validation: Sanitization
While validation checks if data is *correct*, sanitization cleans or modifies data to remove potentially harmful elements. This is especially important for text inputs that will be displayed in a browser.
For example, removing HTML tags from user-submitted comments helps prevent Cross-Site Scripting (XSS) attacks, where malicious scripts could be injected and executed in other users' browsers.
General API Security Best Practices
Beyond input validation and sanitization, consider these practices for robust API security:
- Use HTTPS: Encrypt all communication.
- Implement Authentication & Authorization: Ensure only legitimate, authorized users can access specific endpoints.
- Rate Limiting: Prevent abuse and brute-force attacks by limiting the number of requests a client can make over time.
- CORS Policies: Configure Cross-Origin Resource Sharing (CORS) headers to control which domains can access your API.
- Error Hiding: Avoid revealing sensitive information in error messages (e.g., stack traces).
Validation Quick Check
You're building a Next.js API route to receive user sign-up data. Which of the following is the most critical reason to perform server-side input validation, even if client-side validation is already in place?
Recap: Validate & Secure Your APIs
Great job! You've learned the importance of input validation and security for Next.js API routes.
- Always validate server-side to protect your application.
- Zod is a powerful tool for defining and enforcing data schemas.
- Handle validation errors gracefully with
400 Bad Requestresponses. - Remember to sanitize inputs and follow general API security best practices.
These steps are fundamental to building robust and secure fullstack Next.js applications!
คำถามที่พบบ่อย
บทเรียน “การตรวจสอบคำขอและความปลอดภัย” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การตรวจสอบคำขอและความปลอดภัย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบคำขอและความปลอดภัย”
นำการตรวจสอบข้อมูลนำเข้าไปใช้ และรักษาความปลอดภัยให้เส้นทาง API จากช่องโหว่ทั่วไป คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การตรวจสอบคำขอและความปลอดภัย” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม
ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างตัวจัดการเส้นทาง API
- การตรวจสอบคำขอและความปลอดภัย
- การผสานรวมบริการภายนอก
- การจำกัดอัตราและการจัดการข้อผิดพลาดของ API