Schema definition helps you describe the shape and rules of your data clearly. It makes sure your app uses data correctly and avoids errors.
0
0
Schema definition in NextJS
Introduction
When you want to validate user input before saving it.
When you need to define the structure of data sent between server and client.
When working with databases to ensure data follows expected formats.
When building APIs to document and enforce data contracts.
When you want to catch mistakes early by checking data shapes.
Syntax
NextJS
import { z } from 'zod'; const schema = z.object({ name: z.string(), age: z.number().int().positive(), email: z.string().email().optional() });
This example uses zod, a popular schema library in Next.js projects.
Each field defines the expected type and rules, like string, number, or optional fields.
Examples
Defines a user with a username and password, both strings with minimum lengths.
NextJS
const userSchema = z.object({ username: z.string().min(3), password: z.string().min(8) });
Defines a product with an ID, a non-negative price, and optional tags as an array of strings.
NextJS
const productSchema = z.object({
id: z.string(),
price: z.number().nonnegative(),
tags: z.array(z.string()).optional()
});Defines a response that can be either success with data or failure with an error message.
NextJS
const responseSchema = z.union([ z.object({ success: z.literal(true), data: z.any() }), z.object({ success: z.literal(false), error: z.string() }) ]);
Sample Program
This code defines a user schema and checks if userData matches it. If valid, it prints the user data. If not, it shows errors.
NextJS
import { z } from 'zod'; const userSchema = z.object({ name: z.string(), age: z.number().int().positive(), email: z.string().email().optional() }); // Example data to validate const userData = { name: 'Alice', age: 30, email: 'alice@example.com' }; try { const validatedUser = userSchema.parse(userData); console.log('Valid user:', validatedUser); } catch (e) { console.log('Validation error:', e.errors); }
OutputSuccess
Important Notes
Always validate data before using it to avoid bugs and security issues.
Schema libraries like zod integrate well with Next.js and TypeScript for better developer experience.
Optional fields let you accept data that may or may not be present.
Summary
Schema definition describes the shape and rules of your data.
It helps catch errors early by validating data before use.
Using libraries like zod makes schema definition easy and clear in Next.js projects.