Next.js course ยท Module 6: Forms and Server Actions
Server-side Validation with Server Actions
In this lesson8
Server-side data validation is an inseparable element of security and data integrity in web applications. In the context of Next.js, Server Actions - introduced in Next.js 13 and enhanced in subsequent versions - offer a powerful mechanism for executing server-side logic directly from components. In this module, we will discuss how to effectively implement validation using Server Actions.
Why Do We Need Server-side Validation?
Despite the advantages of client-side validation, server-side validation is necessary for several reasons:
- Security - JavaScript code on the client side can be modified or bypassed
- Data consistency - the server is the final control layer before database modifications
- Complex business rule validation - some rules may require access to server-side data
- Progressive enhancement - ensuring functionality even when JavaScript is disabled
Server Actions Basics in Next.js
Server Actions are functions that run on the server but can be called directly from client-side code. You must mark them with the 'use server' directive - either at the top of the file (so that all functions in the file are Server Actions) or before a specific exported function declaration.
Basic Server Action Structure
// app/actions.ts
'use server'; // All functions exported from this file will be Server Actions
import { z } from 'zod';
// Validation schema
const ContactSchema = z.object({
name: z.string().min(1, { message: 'Name is required' }),
email: z.string().email({ message: 'Invalid email address' }),
message: z.string().min(10, { message: 'Message must be at least 10 characters' })
});
export async function submitContactForm(formData: FormData) {
// Extract data from FormData
const name = formData.get('name');
const email = formData.get('email');
const message = formData.get('message');
// Validate data using Zod
const result = ContactSchema.safeParse({ name, email, message });
if (!result.success) {
// Return validation errors
return {
success: false,
errors: result.error.flatten().fieldErrors
};
}
// Process valid data
try {
// Here would be the code to save the message, send email, etc.
console.log('Valid form data:', result.data);
// Simulate database delay
await new Promise(resolve => setTimeout(resolve, 1000));
return {
success: true,
message: 'Message was sent!'
};
} catch (error) {
console.error('Error while processing the form:', error);
return {
success: false,
message: 'An error occurred while processing the form. Please try again later.'
};
}
}Using Server Action in a Component
// app/contact/page.tsx
'use client';
import { useRef, useState } from 'react';
import { submitContactForm } from '../actions';
type FormErrors = {
name?: string[];
email?: string[];
message?: string[];
};
export default function ContactPage() {
const formRef = useRef<HTMLFormElement>(null);
const [errors, setErrors] = useState<FormErrors>({});
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
async function handleSubmit(formData: FormData) {
setLoading(true);
setErrors({});
setSuccess(false);
const result = await submitContactForm(formData);
setLoading(false);
if (result.success) {
setSuccess(true);
formRef.current?.reset();
} else if (result.errors) {
setErrors(result.errors);
} else if (result.message) {
alert(result.message); // Alternatively can be displayed in the UI
}
}
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">Contact</h1>
{success && (
<div className="mb-4 p-3 bg-green-100 text-green-700 rounded">
Thank you for your message! We will respond as soon as possible.
</div>
)}
<form action={handleSubmit} ref={formRef} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Full name
</label>
<input
type="text"
id="name"
name="name"
className={`mt-1 block w-full rounded-md ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.name && (
<p className="text-red-500 text-xs mt-1">{errors.name[0]}</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
type="email"
id="email"
name="email"
className={`mt-1 block w-full rounded-md ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.email && (
<p className="text-red-500 text-xs mt-1">{errors.email[0]}</p>
)}
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-700">
Message
</label>
<textarea
id="message"
name="message"
rows={4}
className={`mt-1 block w-full rounded-md ${errors.message ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.message && (
<p className="text-red-500 text-xs mt-1">{errors.message[0]}</p>
)}
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Sending...' : 'Send message'}
</button>
</form>
</div>
);
}In this example:
- The form uses the
actionattribute directly with the Server Action - Validation errors are returned to the component and displayed to the user
- The form can be reset after successful submission
Advanced Validation with Multi-step Forms
Example of validation in a multi-step form using Server Actions:
// app/checkout/actions.ts
'use server';
import { z } from 'zod';
// Validation schema for personal data
const PersonalDetailsSchema = z.object({
firstName: z.string().min(1, { message: 'Name is required' }),
lastName: z.string().min(1, { message: 'Last name is required' }),
email: z.string().email({ message: 'Invalid email address' }),
phone: z.string().regex(/^[0-9]{9}$/, { message: 'Phone number must be 9 digits' })
});
// Validation schema for shipping address
const ShippingAddressSchema = z.object({
street: z.string().min(1, { message: 'Street is required' }),
city: z.string().min(1, { message: 'City is required' }),
postalCode: z.string().regex(/^\d{2}-\d{3}$/, { message: 'Postal code must be in XX-XXX format' }),
country: z.string().min(1, { message: 'Country is required' })
});
// Validation schema for payment data
const PaymentDetailsSchema = z.object({
cardholderName: z.string().min(1, { message: 'Name on card is required' }),
cardNumber: z.string().regex(/^[0-9]{16}$/, { message: 'Card number must be 16 digits' }),
expiryDate: z.string().regex(/^(0[1-9]|1[0-2])\/[0-9]{2}$/, { message: 'Expiry date must be in MM/YY format' }),
cvv: z.string().regex(/^[0-9]{3}$/, { message: 'CVV must consist of 3 digits' })
});
// Function to validate personal data
export async function validatePersonalDetails(formData: FormData) {
// Extract data
const data = {
firstName: formData.get('firstName'),
lastName: formData.get('lastName'),
email: formData.get('email'),
phone: formData.get('phone')
};
// Validation
const result = PersonalDetailsSchema.safeParse(data);
if (!result.success) {
return {
success: false,
errors: result.error.flatten().fieldErrors
};
}
// Optionally: save data to session
// await saveToSession('personalDetails', result.data);
return {
success: true,
data: result.data
};
}
// Function to validate shipping address
export async function validateShippingAddress(formData: FormData) {
const data = {
street: formData.get('street'),
city: formData.get('city'),
postalCode: formData.get('postalCode'),
country: formData.get('country')
};
const result = ShippingAddressSchema.safeParse(data);
if (!result.success) {
return {
success: false,
errors: result.error.flatten().fieldErrors
};
}
return {
success: true,
data: result.data
};
}
// Function to validate payment data
export async function validatePaymentDetails(formData: FormData) {
const data = {
cardholderName: formData.get('cardholderName'),
cardNumber: formData.get('cardNumber'),
expiryDate: formData.get('expiryDate'),
cvv: formData.get('cvv')
};
const result = PaymentDetailsSchema.safeParse(data);
if (!result.success) {
return {
success: false,
errors: result.error.flatten().fieldErrors
};
}
return {
success: true,
data: result.data
};
}
// Function to finalize the order
export async function submitOrder(personalDetails: any, shippingAddress: any, paymentDetails: any) {
try {
// Here would be the code for processing payment and saving the order
console.log('Processing order:', { personalDetails, shippingAddress, paymentDetails });
// Simulate delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Generate order number
const orderNumber = Math.floor(100000 + Math.random() * 900000).toString();
return {
success: true,
orderNumber
};
} catch (error) {
console.error('Error while processing the order:', error);
return {
success: false,
message: 'An error occurred while processing the order. Please try again later.'
};
}
}And the client component using these actions:
// app/checkout/page.tsx
'use client';
import { useState } from 'react';
import { validatePersonalDetails, validateShippingAddress, validatePaymentDetails, submitOrder } from './actions';
// Error types for each step
type FormErrors = Record<string, string[]>;
export default function CheckoutPage() {
// States for tracking step, data and errors
const [currentStep, setCurrentStep] = useState(1);
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState<FormErrors>({});
const [formData, setFormData] = useState({
personalDetails: null,
shippingAddress: null,
paymentDetails: null
});
const [orderResult, setOrderResult] = useState<{ success: boolean; orderNumber?: string; message?: string } | null>(null);
// Function to handle step 1 - personal data
async function handlePersonalDetailsSubmit(formData: FormData) {
setLoading(true);
setErrors({});
const result = await validatePersonalDetails(formData);
setLoading(false);
if (result.success) {
setFormData(prev => ({ ...prev, personalDetails: result.data }));
setCurrentStep(2);
} else if (result.errors) {
setErrors(result.errors);
}
}
// Function to handle step 2 - shipping address
async function handleShippingAddressSubmit(formData: FormData) {
setLoading(true);
setErrors({});
const result = await validateShippingAddress(formData);
setLoading(false);
if (result.success) {
setFormData(prev => ({ ...prev, shippingAddress: result.data }));
setCurrentStep(3);
} else if (result.errors) {
setErrors(result.errors);
}
}
// Function to handle step 3 - payment data
async function handlePaymentDetailsSubmit(formData: FormData) {
setLoading(true);
setErrors({});
const result = await validatePaymentDetails(formData);
setLoading(false);
if (result.success) {
setFormData(prev => ({ ...prev, paymentDetails: result.data }));
// After validating all steps, we submit the order
await finalizeOrder(result.data);
} else if (result.errors) {
setErrors(result.errors);
}
}
// Finalize order
async function finalizeOrder(paymentDetails: any) {
setLoading(true);
const { personalDetails, shippingAddress } = formData;
const result = await submitOrder(personalDetails, shippingAddress, paymentDetails);
setLoading(false);
setOrderResult(result);
if (result.success) {
setCurrentStep(4); // Move to confirmation
}
}
// Return to previous step
function goToPreviousStep() {
setCurrentStep(prev => Math.max(1, prev - 1));
setErrors({});
}
// Reset form
function resetForm() {
setCurrentStep(1);
setFormData({
personalDetails: null,
shippingAddress: null,
paymentDetails: null
});
setErrors({});
setOrderResult(null);
}
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">Order Processing</h1>
{/* Progress bar */}
<div className="mb-6">
<div className="flex justify-between">
{['Personal data', 'Shipping address', 'Payment', 'Confirmation'].map((step, index) => (
<div key={index} className="flex flex-col items-center">
<div className={`h-8 w-8 rounded-full flex items-center justify-center text-sm ${currentStep > index + 1 ? 'bg-green-500 text-white' : currentStep === index + 1 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'}`}>
{currentStep > index + 1 ? 'โ' : index + 1}
</div>
<span className="text-xs mt-1">{step}</span>
</div>
))}
</div>
<div className="mt-2 h-2 bg-gray-200 rounded-full">
<div
className="h-full bg-blue-600 rounded-full transition-all duration-300"
style={{ width: `${Math.min(100, ((currentStep - 1) / 3) * 100)}%` }}
></div>
</div>
</div>
{/* Step 1: Personal data */}
{currentStep === 1 && (
<form action={handlePersonalDetailsSubmit} className="space-y-4">
<div>
<label htmlFor="firstName" className="block text-sm font-medium text-gray-700">First name</label>
<input
type="text"
id="firstName"
name="firstName"
defaultValue={formData.personalDetails?.firstName || ''}
className={`mt-1 block w-full rounded-md ${errors.firstName ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.firstName && <p className="text-red-500 text-xs mt-1">{errors.firstName[0]}</p>}
</div>
<div>
<label htmlFor="lastName" className="block text-sm font-medium text-gray-700">Last name</label>
<input
type="text"
id="lastName"
name="lastName"
defaultValue={formData.personalDetails?.lastName || ''}
className={`mt-1 block w-full rounded-md ${errors.lastName ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.lastName && <p className="text-red-500 text-xs mt-1">{errors.lastName[0]}</p>}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">Email</label>
<input
type="email"
id="email"
name="email"
defaultValue={formData.personalDetails?.email || ''}
className={`mt-1 block w-full rounded-md ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.email && <p className="text-red-500 text-xs mt-1">{errors.email[0]}</p>}
</div>
<div>
<label htmlFor="phone" className="block text-sm font-medium text-gray-700">Phone</label>
<input
type="tel"
id="phone"
name="phone"
defaultValue={formData.personalDetails?.phone || ''}
className={`mt-1 block w-full rounded-md ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.phone && <p className="text-red-500 text-xs mt-1">{errors.phone[0]}</p>}
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Processing...' : 'Next'}
</button>
</form>
)}
{/* Step 2: Shipping address */}
{currentStep === 2 && (
<form action={handleShippingAddressSubmit} className="space-y-4">
<div>
<label htmlFor="street" className="block text-sm font-medium text-gray-700">Street and number</label>
<input
type="text"
id="street"
name="street"
defaultValue={formData.shippingAddress?.street || ''}
className={`mt-1 block w-full rounded-md ${errors.street ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.street && <p className="text-red-500 text-xs mt-1">{errors.street[0]}</p>}
</div>
<div>
<label htmlFor="city" className="block text-sm font-medium text-gray-700">City</label>
<input
type="text"
id="city"
name="city"
defaultValue={formData.shippingAddress?.city || ''}
className={`mt-1 block w-full rounded-md ${errors.city ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.city && <p className="text-red-500 text-xs mt-1">{errors.city[0]}</p>}
</div>
<div>
<label htmlFor="postalCode" className="block text-sm font-medium text-gray-700">Postal code</label>
<input
type="text"
id="postalCode"
name="postalCode"
defaultValue={formData.shippingAddress?.postalCode || ''}
className={`mt-1 block w-full rounded-md ${errors.postalCode ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.postalCode && <p className="text-red-500 text-xs mt-1">{errors.postalCode[0]}</p>}
</div>
<div>
<label htmlFor="country" className="block text-sm font-medium text-gray-700">Country</label>
<select
id="country"
name="country"
defaultValue={formData.shippingAddress?.country || ''}
className={`mt-1 block w-full rounded-md ${errors.country ? 'border-red-500' : 'border-gray-300'}`}
>
<option value="">Select country</option>
<option value="Poland">Poland</option>
<option value="Germany">Germany</option>
<option value="UK">United Kingdom</option>
<option value="France">France</option>
</select>
{errors.country && <p className="text-red-500 text-xs mt-1">{errors.country[0]}</p>}
</div>
<div className="flex justify-between">
<button
type="button"
onClick={goToPreviousStep}
className="py-2 px-4 border border-gray-300 rounded-md hover:bg-gray-50"
>
Back
</button>
<button
type="submit"
disabled={loading}
className="py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Processing...' : 'Next'}
</button>
</div>
</form>
)}
{/* Step 3: Payment data */}
{currentStep === 3 && (
<form action={handlePaymentDetailsSubmit} className="space-y-4">
<div>
<label htmlFor="cardholderName" className="block text-sm font-medium text-gray-700">Name on card</label>
<input
type="text"
id="cardholderName"
name="cardholderName"
className={`mt-1 block w-full rounded-md ${errors.cardholderName ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.cardholderName && <p className="text-red-500 text-xs mt-1">{errors.cardholderName[0]}</p>}
</div>
<div>
<label htmlFor="cardNumber" className="block text-sm font-medium text-gray-700">Card number</label>
<input
type="text"
id="cardNumber"
name="cardNumber"
className={`mt-1 block w-full rounded-md ${errors.cardNumber ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.cardNumber && <p className="text-red-500 text-xs mt-1">{errors.cardNumber[0]}</p>}
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="expiryDate" className="block text-sm font-medium text-gray-700">Expiry date</label>
<input
type="text"
id="expiryDate"
name="expiryDate"
className={`mt-1 block w-full rounded-md ${errors.expiryDate ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.expiryDate && <p className="text-red-500 text-xs mt-1">{errors.expiryDate[0]}</p>}
</div>
<div>
<label htmlFor="cvv" className="block text-sm font-medium text-gray-700">CVV</label>
<input
type="text"
id="cvv"
name="cvv"
className={`mt-1 block w-full rounded-md ${errors.cvv ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.cvv && <p className="text-red-500 text-xs mt-1">{errors.cvv[0]}</p>}
</div>
</div>
<div className="flex justify-between">
<button
type="button"
onClick={goToPreviousStep}
className="py-2 px-4 border border-gray-300 rounded-md hover:bg-gray-50"
>
Back
</button>
<button
type="submit"
disabled={loading}
className="py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Processing payment...' : 'Place order'}
</button>
</div>
</form>
)}
{/* Step 4: Confirmation */}
{currentStep === 4 && orderResult?.success && (
<div className="text-center py-8">
<div className="mb-4 w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto">
<svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<h2 className="text-2xl font-bold mb-2">Order accepted!</h2>
<p className="text-gray-600 mb-1">Thank you for placing your order.</p>
<p className="text-gray-600 mb-4">Order number: <span className="font-medium">{orderResult.orderNumber}</span></p>
<p className="text-sm text-gray-500 mb-6">Order details have been sent to email: <br />{formData.personalDetails?.email}</p>
<button
onClick={resetForm}
className="inline-block py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
Place new order
</button>
</div>
)}
{/* Finalization error message */}
{currentStep === 3 && orderResult?.success === false && (
<div className="mt-4 p-3 bg-red-100 text-red-700 rounded">
{orderResult.message || 'An error occurred while processing the order.'}
</div>
)}
</div>
);
}Using useFormStatus and useActionState
Next.js provides the useFormStatus and useActionState hooks, which provide better integration with Server Actions in forms:
// app/contact/actions.ts
'use server';
import { z } from 'zod';
// Validation schema
const ContactSchema = z.object({
name: z.string().min(1, { message: 'Name is required' }),
email: z.string().email({ message: 'Invalid email address' }),
message: z.string().min(10, { message: 'Message must be at least 10 characters' })
});
// Form state type
type FormState = {
errors?: {
name?: string[];
email?: string[];
message?: string[];
};
message?: string;
success?: boolean;
};
// Server Action with return format for useActionState
export async function submitContactForm(prevState: FormState, formData: FormData): Promise<FormState> {
// Extract data
const name = formData.get('name');
const email = formData.get('email');
const message = formData.get('message');
// Validation
const result = ContactSchema.safeParse({ name, email, message });
if (!result.success) {
return {
errors: result.error.flatten().fieldErrors,
message: 'Fix the errors in the form',
success: false
};
}
try {
// Save message to database, send email, etc.
await new Promise(resolve => setTimeout(resolve, 1000));
// In a real application, here would be the form processing code
console.log('Contact message:', result.data);
return {
errors: {},
message: 'Message was sent!',
success: true
};
} catch (error) {
return {
errors: {},
message: 'An error occurred. Please try again later.',
success: false
};
}
}And the corresponding form component:
// app/contact/page.tsx
'use client';
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
import { submitContactForm } from './actions';
// Button component with form state handling
function SubmitButton() {
// useFormStatus gives access to form state, including pending
const { pending } = useFormStatus();
return (
<button
type="submit"
disabled={pending}
className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{pending ? 'Sending...' : 'Send message'}
</button>
);
}
export default function ContactPage() {
// Initialize form state
const initialState = { errors: {}, message: '', success: false };
// useActionState (connects form with Server Action)
const [state, formAction] = useActionState(submitContactForm, initialState);
// Reset form after successful submission
const formRef = React.useRef<HTMLFormElement>(null);
React.useEffect(() => {
if (state.success && formRef.current) {
formRef.current.reset();
}
}, [state.success]);
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">Contact</h1>
{state.message && (
<div className={`mb-4 p-3 rounded ${state.success ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
{state.message}
</div>
)}
<form ref={formRef} action={formAction} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Full name
</label>
<input
type="text"
id="name"
name="name"
className={`mt-1 block w-full rounded-md ${state.errors?.name ? 'border-red-500' : 'border-gray-300'}`}
/>
{state.errors?.name && (
<p className="text-red-500 text-xs mt-1">{state.errors.name[0]}</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
type="email"
id="email"
name="email"
className={`mt-1 block w-full rounded-md ${state.errors?.email ? 'border-red-500' : 'border-gray-300'}`}
/>
{state.errors?.email && (
<p className="text-red-500 text-xs mt-1">{state.errors.email[0]}</p>
)}
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-700">
Message
</label>
<textarea
id="message"
name="message"
rows={4}
className={`mt-1 block w-full rounded-md ${state.errors?.message ? 'border-red-500' : 'border-gray-300'}`}
/>
{state.errors?.message && (
<p className="text-red-500 text-xs mt-1">{state.errors.message[0]}</p>
)}
</div>
<SubmitButton />
</form>
</div>
);
}Key advantages of this approach:
- useFormStatus - allows easy tracking of the form's pending state
- useActionState - provides automatic state management between server and client
- Progressive enhancement - the form works even without JavaScript
Validation with TypeScript and Zod
Zod integrates excellently with TypeScript, allowing you to define validation schemas that simultaneously serve as types:
// app/lib/validationSchemas.ts
import { z } from 'zod';
// Product schema
export const ProductSchema = z.object({
name: z.string().min(1, { message: 'Product name is required' }),
price: z.coerce.number().min(0.01, { message: 'Price must be greater than 0' }),
description: z.string().min(10, { message: 'Description must be at least 10 characters' }),
category: z.enum(['electronics', 'clothing', 'food', 'books'], {
errorMap: () => ({ message: 'Select a valid category' })
}),
quantity: z.coerce.number().int().min(0, { message: 'Quantity cannot be negative' }),
featured: z.boolean().default(false)
});
// Product type inferred from schema
export type Product = z.infer<typeof ProductSchema>;
// Schema for editing product (all fields optional)
export const ProductUpdateSchema = ProductSchema.partial();
export type ProductUpdate = z.infer<typeof ProductUpdateSchema>;Usage in a Server Action:
// app/products/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { ProductSchema, ProductUpdateSchema, type Product } from '../lib/validationSchemas';
// Function to add a new product
export async function addProduct(formData: FormData) {
// Convert FormData to object
const rawData = Object.fromEntries(formData.entries());
// Convert 'featured' field to boolean (checkbox)
const productData = {
...rawData,
featured: formData.get('featured') === 'on'
};
// Validate data
const validationResult = ProductSchema.safeParse(productData);
if (!validationResult.success) {
return {
success: false,
errors: validationResult.error.flatten().fieldErrors
};
}
try {
// In a real application: save product to database
// const newProduct = await db.product.create({ data: validationResult.data });
console.log('Added new product:', validationResult.data);
// Revalidate path to refresh cache
revalidatePath('/products');
return {
success: true,
message: 'Product was added successfully!'
};
} catch (error) {
console.error('Error while adding product:', error);
return {
success: false,
message: 'An error occurred while adding the product.'
};
}
}
// Function to update product (all fields optional)
export async function updateProduct(id: string, formData: FormData) {
const rawData = Object.fromEntries(formData.entries());
// Remove empty fields that should not be updated
for (const [key, value] of Object.entries(rawData)) {
if (value === '') {
delete rawData[key];
}
}
// Convert 'featured' field to boolean (checkbox)
const productData = {
...rawData,
featured: formData.has('featured')
};
// Validate partial update
const validationResult = ProductUpdateSchema.safeParse(productData);
if (!validationResult.success) {
return {
success: false,
errors: validationResult.error.flatten().fieldErrors
};
}
try {
// In a real application: update product in database
// const updatedProduct = await db.product.update({
// where: { id },
// data: validationResult.data
// });
console.log(`Updated product ${id}:`, validationResult.data);
// Revalidate path to refresh cache
revalidatePath(`/products/${id}`);
revalidatePath('/products');
return {
success: true,
message: 'Product was updated successfully!'
};
} catch (error) {
console.error('Error while updating product:', error);
return {
success: false,
message: 'An error occurred while updating the product.'
};
}
}Security in Server Actions
When implementing validation in Server Actions, several key security considerations must be kept in mind:
1. CSRF (Cross-Site Request Forgery) Protection
Next.js automatically protects Server Actions against CSRF attacks via so-called "Action IDs" and other mechanisms. However, it's good to be aware of this protection and apply additional safeguards in critical operations.
2. Rate Limiting
For sensitive operations (e.g. login, registration) it's worth applying a limit on the number of requests from a single IP address:
'use server';
import { cookies } from 'next/headers';
// Simple cookie-based rate limiting implementation
export async function loginUser(formData: FormData) {
const cookieStore = await cookies();
const attemptsCookie = cookieStore.get('login_attempts');
// Check number of login attempts
const attempts = attemptsCookie ? parseInt(attemptsCookie.value, 10) : 0;
if (attempts >= 5) {
return {
success: false,
message: 'Too many login attempts. Please try again later.'
};
}
// Rest of login logic...
// On failed login, increment the counter
if (!success) {
(await cookies()).set('login_attempts', String(attempts + 1), {
maxAge: 60 * 15, // 15 minutes
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
});
} else {
// Reset counter after successful login
(await cookies()).set('login_attempts', '0');
}
//
}3. Input Data Sanitization
Always sanitize and validate input data before processing:
'use server';
import { z } from 'zod';
import { sanitizeHtml } from 'some-html-sanitizer';
export async function addComment(formData: FormData) {
// Retrieve and initial sanitization
const rawComment = formData.get('comment')?.toString() || '';
const sanitizedComment = sanitizeHtml(rawComment, {
allowedTags: ['b', 'i', 'em', 'strong'],
allowedAttributes: {}
});
// Validation after sanitization
const commentSchema = z.string().min(5).max(1000);
const result = commentSchema.safeParse(sanitizedComment);
if (!result.success) {
return { success: false, errors: result.error.flatten().formErrors };
}
// Save to database...
}4. Authorization in Server Actions
Always check user permissions before executing an operation:
'use server';
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth';
export async function deleteProduct(productId: string) {
// Get user session
const session = await getServerSession(authOptions);
// Check if user is logged in
if (!session?.user) {
return {
success: false,
message: 'You must be logged in to perform this operation.'
};
}
// Check additional permissions (e.g. admin role)
if (session.user.role !== 'admin') {
return {
success: false,
message: 'You do not have permission to perform this operation.'
};
}
// Execute operation...
}Best Practices for Data Validation in Server Actions
Client + server validation combination - validate on the client for better UX, but always verify on the server
Consistent error messages - use the same messages on both sides
Progressive enhancement - ensure forms work even without JavaScript
End-to-end typing - use Zod type inference for consistency between client and server
Data revalidation - use
revalidatePathorrevalidateTagafter mutations to refresh the cacheError structure - maintain a consistent response format for errors
Minimize client state - keep as much logic as possible on the server
Consider accessibility - use appropriate error descriptions and ARIA attributes
Summary
Server Actions in Next.js provide a powerful mechanism for implementing server-side validation that combines security benefits with a good user experience:
- Security - data is always validated on the server, regardless of the client's JavaScript state
- Performance - no need to create separate API endpoints
- Progressive enhancement - forms work even without JavaScript
- Type consistency - the ability to share validation schemas between client and server
By applying the techniques and best practices described in this module, you can build robust, secure, and user-friendly forms that take full advantage of Next.js capabilities.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Simulation of server-side validation with Server Actions in Next.js
type ServerState = {
status: 'idle' | 'pending' | 'success' | 'error';
errors: Record<string, string>;
message: string;
};
// Simulation Server Action
async function simulateServerAction(formData: Record<string, string>): Promise<ServerState> {
// Simulation of server delay
await new Promise(r => setTimeout(r, 1000));
const errors: Record<string, string> = {};
// Server-side validation - independent of the client
if (!formData.title || formData.title.length < 3) {
errors.title = 'Title must have at least 3 characters';
}
if (!formData.content || formData.content.length < 10) {
errors.content = 'Content must have at least 10 characters';
}
if (formData.title?.toLowerCase().includes('test')) {
errors.title = 'Server rejected it: the word "test" is forbidden';
}
if (Object.keys(errors).length > 0) {
return { status: 'error', errors, message: 'Server-side validation failed' };
}
return { status: 'success', errors: {}, message: 'Data saved on the server!' };
}
export default function ServerValidationDemo() {
const [values, setValues] = useState({ title: '', content: '' });
const [state, setState] = useState<ServerState>({ status: 'idle', errors: {}, message: '' });
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setState({ status: 'pending', errors: {}, message: 'Validating on the server...' });
const result = await simulateServerAction(values);
setState(result);
};
const inputStyle: React.CSSProperties = {
width: '100%', padding: '10px', background: '#0d1117',
border: '1px solid #333', borderRadius: 6, color: '#e0e0e0',
fontFamily: 'monospace', fontSize: 13, boxSizing: 'border-box'
};
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>Server Actions - server-side validation</h1>
<p style={{ color: '#888', fontSize: 13, marginBottom: 16 }}>
Data is validated on the server - independent of client-side JavaScript.
Try using the word "test" in the title!
</p>
<div style={{ background: '#0d1117', borderRadius: 8, padding: 12, marginBottom: 16 }}>
<pre style={{ color: '#ce93d8', fontSize: 11, margin: 0 }}>
{/* Server Action example */}
{'// app/actions.ts\n"use server"\n\nexport async function createPost(formData: FormData) {\n const title = formData.get("title");\n // server-side validation...\n}'}
</pre>
</div>
<form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
<div style={{ marginBottom: 12 }}>
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Title</label>
<input
value={values.title}
onChange={e => setValues(p => ({ ...p, title: e.target.value }))}
style={{ ...inputStyle, borderColor: state.errors.title ? '#f44336' : '#333' }}
/>
{state.errors.title && <div style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{state.errors.title}</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Content (min 10 characters)</label>
<textarea
value={values.content}
onChange={e => setValues(p => ({ ...p, content: e.target.value }))}
rows={3}
style={{ ...inputStyle, resize: 'vertical', borderColor: state.errors.content ? '#f44336' : '#333' }}
/>
{state.errors.content && <div style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{state.errors.content}</div>}
</div>
<button type="submit" disabled={state.status === 'pending'} style={{
background: state.status === 'pending' ? '#555' : '#ff9800',
color: '#fff', border: 'none', borderRadius: 6,
padding: '10px 20px', cursor: state.status === 'pending' ? 'wait' : 'pointer',
fontFamily: 'monospace', width: '100%'
}}>
{state.status === 'pending' ? 'Validating on the server...' : 'Submit (Server Action)'}
</button>
</form>
{state.message && state.status !== 'idle' && (
<div style={{
marginTop: 16, borderRadius: 8, padding: 12, maxWidth: 400,
background: state.status === 'success' ? '#1b5e20' : state.status === 'error' ? '#3e2723' : '#1a2744',
border: `1px solid ${state.status === 'success' ? '#4caf50' : state.status === 'error' ? '#f44336' : '#2196f3'}`,
}}>
<div style={{ color: state.status === 'success' ? '#4caf50' : state.status === 'error' ? '#f44336' : '#2196f3' }}>
{state.message}
</div>
</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. Server Actions in Next.js allow you to:
2. Formik is:
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a registration form using React Hook Form with fields: username, email, password, confirmPassword
- Horizontal ordering
Arrange the input syntax with register in React Hook Form
- Click in order
Arrange the Zod schema definition syntax
- Code editor
Create a Zod schema for a user form with email validation, strong password, min/max lengths
- Code editor
Create a Server Action for processing a contact form with validation and email sending
- Vertical ordering
Arrange the elements in the correct order: Install package โ Import components โ Customize theme โ Use in app
- Click in order
Arrange the input registration syntax in React Hook Form
- Code editor
Create a multi-step registration form with steps: Personal Info, Account Details, Preferences
Tasks after this lesson
- QuestionServer Actions in Next.js allow you to:
- QuestionFormik is:
- Coding taskPractice: Create a registration form using React Hook
- Put in orderInput syntax with register in React Hook Form
- Click in orderSequence: const โ schema โ =
- Coding taskPractice: Create a Zod schema for a user form with
- QuestionProgressive Enhancement in forms means:
- QuestionThe useActionState hook in React is used for:
- Coding taskPractice: Create a Server Action for form processing
- Put in orderSequence: Install package โ Import components โ ...
- Click in orderInput syntax with register
- Coding taskPractice: Create a multi-step registration form with