Bird
Raised Fist0
NextJSframework~10 mins

Schema definition in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Schema definition
Define schema object
Specify fields and types
Add validation rules
Export schema for use
Use schema to validate data
Handle validation result
This flow shows how to create a schema, add rules, export it, and use it to check data.
Execution Sample
NextJS
import { z } from 'zod';

const userSchema = z.object({
  name: z.string(),
  age: z.number().int().positive()
});

export default userSchema;
Defines a schema for a user with a name string and a positive integer age.
Execution Table
StepActionEvaluationResult
1Import zod libraryz importedz object available
2Define userSchema with name and agez.object calleduserSchema created
3Add name field as stringz.string()name field validated as string
4Add age field as positive integerz.number().int().positive()age field validated as positive int
5Export userSchemaexport statementschema ready for use
6Validate data {name: 'Alice', age: 30}userSchema.parse()passes validation
7Validate data {name: 'Bob', age: -5}userSchema.parse()throws validation error
8Validate data {name: 123, age: 20}userSchema.parse()throws validation error
💡 Validation stops when data matches schema or error is thrown
Variable Tracker
VariableStartAfter Step 2After Step 5After Step 6After Step 7After Step 8
userSchemaundefinedobject with fieldsexported schema objectvalidates Alice datathrows error for negative agethrows error for wrong name type
Key Moments - 2 Insights
Why does validation fail when age is negative?
Because the schema requires age to be positive as shown in step 4 and step 7 of the execution_table.
Why does validation fail when name is a number?
Because the schema expects name to be a string, so passing a number breaks the rule as shown in step 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of validating {name: 'Alice', age: 30} at step 6?
Apasses validation
Bthrows validation error
Cskips validation
Dreturns undefined
💡 Hint
Check the 'Result' column at step 6 in execution_table
At which step does the schema add the rule that age must be a positive integer?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look at the 'Action' and 'Evaluation' columns in execution_table for age field
If we change the age rule to allow zero, how would the validation result change for age 0?
AValidation would still fail for age 0
BValidation would pass for age 0
CValidation would throw a different error
DValidation would ignore age field
💡 Hint
Consider the positive() rule in step 4 and how removing it affects validation
Concept Snapshot
Schema definition in Next.js uses libraries like zod.
Define a schema object with fields and types.
Add validation rules like string(), number(), positive().
Export schema and use parse() to validate data.
Validation passes if data matches rules, else throws error.
Full Transcript
In Next.js, schema definition is done by creating an object that describes the shape and rules for data. We import a library like zod, then define a schema object with fields such as name and age. Each field has a type and validation rules, for example, name must be a string and age must be a positive integer. After defining, we export the schema to use it elsewhere. When validating data, we call parse() on the schema with the data. If the data matches the schema, validation passes. If not, it throws an error. This helps ensure data is correct before using it in the app.

Practice

(1/5)
1. What is the main purpose of schema definition in a Next.js project?
easy
A. To manage server-side rendering
B. To describe the shape and rules of your data
C. To style the user interface components
D. To handle routing between pages

Solution

  1. Step 1: Understand schema definition role

    Schema definition is about specifying how data should look and behave.
  2. Step 2: Identify its main use in Next.js

    It helps validate data to catch errors early before using it in the app.
  3. Final Answer:

    To describe the shape and rules of your data -> Option B
  4. Quick Check:

    Schema = Data shape and rules [OK]
Hint: Schema defines data shape and validation rules [OK]
Common Mistakes:
  • Confusing schema with UI styling
  • Thinking schema manages routing
  • Assuming schema handles rendering
2. Which of the following is the correct way to define a simple string schema using the zod library in Next.js?
easy
A. const schema = z.string();
B. const schema = z.string;
C. const schema = z.String();
D. const schema = new z.string();

Solution

  1. Step 1: Recall zod syntax for string schema

    In zod, string schema is created by calling z.string() as a function.
  2. Step 2: Check each option's syntax

    const schema = z.string(); uses z.string() correctly. Others miss parentheses or use wrong casing or new keyword.
  3. Final Answer:

    const schema = z.string(); -> Option A
  4. Quick Check:

    z.string() is correct syntax [OK]
Hint: Use parentheses to call z.string() function [OK]
Common Mistakes:
  • Omitting parentheses after z.string
  • Using uppercase 'String' instead of 'string'
  • Using 'new' keyword incorrectly
3. Given this schema definition using zod:
const userSchema = z.object({
name: z.string(),
age: z.number().min(18)
});
const result = userSchema.safeParse({ name: "Alice", age: 16 });
console.log(result.success);

What will be logged to the console?
medium
A. true
B. Throws an error
C. false
D. undefined

Solution

  1. Step 1: Understand schema rules

    The schema requires 'name' as string and 'age' as number at least 18.
  2. Step 2: Check input data against schema

    Input has age 16, which is less than minimum 18, so validation fails.
  3. Final Answer:

    false -> Option C
  4. Quick Check:

    Validation fails because age < 18 [OK]
Hint: Check min() constraints carefully in validation [OK]
Common Mistakes:
  • Assuming validation passes despite age < 18
  • Confusing safeParse result with direct parse
  • Expecting an error instead of false success
4. Identify the error in this Next.js schema definition using zod:
const productSchema = z.object({
id: z.number,
title: z.string(),
price: z.number()
});
medium
A. Missing comma after 'title' property
B. Schema object should be an array
C. Using z.string() incorrectly
D. Missing parentheses after z.number for 'id'

Solution

  1. Step 1: Check each property schema syntax

    'id' uses z.number without parentheses, which is incorrect syntax.
  2. Step 2: Verify other properties and object structure

    Other properties are correct; object schema is correctly defined as an object, not array.
  3. Final Answer:

    Missing parentheses after z.number for 'id' -> Option D
  4. Quick Check:

    z.number() needs parentheses [OK]
Hint: Always call zod types as functions with () [OK]
Common Mistakes:
  • Forgetting parentheses after z.number or z.string
  • Thinking schema must be an array
  • Missing commas between properties
5. You want to define a schema for a user profile in Next.js using zod where the 'email' field is optional but if present must be a valid email string. Which schema definition is correct?
hard
A. const userProfileSchema = z.object({ email: z.string().email().optional() });
B. const userProfileSchema = z.object({ email: z.optional(z.string().email) });
C. const userProfileSchema = z.object({ email: z.string().optional().email() });
D. const userProfileSchema = z.object({ email: z.string().email() || undefined });

Solution

  1. Step 1: Understand optional email schema in zod

    To make a field optional but validate if present, use .optional() after .email().
  2. Step 2: Check each option's method chaining

    const userProfileSchema = z.object({ email: z.string().email().optional() }); correctly chains z.string().email().optional(). const userProfileSchema = z.object({ email: z.optional(z.string().email) }); uses z.optional incorrectly. const userProfileSchema = z.object({ email: z.string().optional().email() }); calls optional before email, which breaks validation. const userProfileSchema = z.object({ email: z.string().email() || undefined }); uses invalid syntax.
  3. Final Answer:

    const userProfileSchema = z.object({ email: z.string().email().optional() }); -> Option A
  4. Quick Check:

    Use .optional() after .email() for optional validated fields [OK]
Hint: Chain .optional() after .email() for optional email fields [OK]
Common Mistakes:
  • Placing .optional() before .email()
  • Using z.optional() wrapper incorrectly
  • Trying to use || undefined for optional