Next.js course Β· Module 6: Forms and Server Actions
Multi-step forms and flows
In this lesson7
Creating complex, multi-step forms is a common task in web applications. Such forms are frequently used for registration processes, reservations, orders, or product configuration. In this module, we'll look at various strategies for implementing multi-step forms in React and Next.js environments.
Why split forms into stages?
Splitting a long form into smaller steps brings many benefits:
- Better user experience - shorter forms are less overwhelming and reduce the risk of abandonment
- Greater clarity - users can more easily focus on one aspect of the process at a time
- Progressive data collection - we can validate each step separately and adjust subsequent stages based on earlier responses
- Logical organization - grouping related form fields improves structure and understanding
- Partial save capability - users can save their progress and return later
Basic approaches to multi-step forms
There are several main approaches to implementing multi-step forms:
1. Component-state based approach
The simplest way is to store the current step and all form data in component state:
'use client';
import { useState, FormEvent } from 'react';
// Data types for individual steps
interface UserDetails {
firstName: string;
lastName: string;
email: string;
}
interface AddressDetails {
street: string;
city: string;
zipCode: string;
country: string;
}
interface PaymentDetails {
cardNumber: string;
expiryDate: string;
cvv: string;
}
// Combined form data
interface FormData {
user: UserDetails;
address: AddressDetails;
payment: PaymentDetails;
}
export default function MultiStepForm() {
// Current step state
const [step, setStep] = useState(1);
// Form data state
const [formData, setFormData] = useState<FormData>({
user: {
firstName: '',
lastName: '',
email: ''
},
address: {
street: '',
city: '',
zipCode: '',
country: ''
},
payment: {
cardNumber: '',
expiryDate: '',
cvv: ''
}
});
// Validation state
const [errors, setErrors] = useState<Record<string, string>>({});
// Handle form field changes
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = e.target;
// Determine which step the field belongs to
if (['firstName', 'lastName', 'email'].includes(name)) {
setFormData({
...formData,
user: {
...formData.user,
[name]: value
}
});
} else if (['street', 'city', 'zipCode', 'country'].includes(name)) {
setFormData({
...formData,
address: {
...formData.address,
[name]: value
}
});
} else if (['cardNumber', 'expiryDate', 'cvv'].includes(name)) {
setFormData({
...formData,
payment: {
...formData.payment,
[name]: value
}
});
}
// Remove error after field edit
if (errors[name]) {
setErrors({
...errors,
[name]: ''
});
}
}
// Validate form data for each step
function validateStep(stepNumber: number): boolean {
const newErrors: Record<string, string> = {};
if (stepNumber === 1) {
// Validate user data
if (!formData.user.firstName.trim()) {
newErrors.firstName = 'Name is required';
}
if (!formData.user.lastName.trim()) {
newErrors.lastName = 'Last name is required';
}
if (!formData.user.email.trim()) {
newErrors.email = 'Email is required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(formData.user.email)) {
newErrors.email = 'Invalid email address format';
}
} else if (stepNumber === 2) {
// Address validation
if (!formData.address.street.trim()) {
newErrors.street = 'Street is required';
}
if (!formData.address.city.trim()) {
newErrors.city = 'City is required';
}
if (!formData.address.zipCode.trim()) {
newErrors.zipCode = 'Postal code is required';
}
if (!formData.address.country.trim()) {
newErrors.country = 'Country is required';
}
} else if (stepNumber === 3) {
// Payment validation
if (!formData.payment.cardNumber.trim()) {
newErrors.cardNumber = 'Card number is required';
} else if (!/^\d{16}$/.test(formData.payment.cardNumber.replace(/\s/g, ''))) {
newErrors.cardNumber = 'Invalid card number';
}
if (!formData.payment.expiryDate.trim()) {
newErrors.expiryDate = 'Expiry date is required';
}
if (!formData.payment.cvv.trim()) {
newErrors.cvv = 'CVV code is required';
} else if (!/^\d{3,4}$/.test(formData.payment.cvv)) {
newErrors.cvv = 'Invalid CVV code';
}
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}
// Move to next step
function handleNext() {
const isValid = validateStep(step);
if (isValid) {
setStep(step + 1);
}
}
// Return to previous step
function handlePrevious() {
setStep(step - 1);
}
// Submit the entire form
function handleSubmit(e: FormEvent) {
e.preventDefault();
const isValid = validateStep(step);
if (isValid) {
// Code for sending data to the API
console.log('Submitting form data:', formData);
// Example API call (in a real application)
// await fetch('/api/checkout', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(formData)
// });
// Optionally: redirect to confirmation page
// router.push('/checkout/success');
}
}
// Render the appropriate step
function renderStep() {
switch (step) {
case 1:
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Personal data</h2>
<div>
<label htmlFor="firstName" className="block text-sm font-medium text-gray-700">
First name
</label>
<input
type="text"
id="firstName"
name="firstName"
value={formData.user.firstName}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.firstName ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.firstName && (
<p className="mt-1 text-sm text-red-600">{errors.firstName}</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"
value={formData.user.lastName}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.lastName ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.lastName && (
<p className="mt-1 text-sm text-red-600">{errors.lastName}</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
type="email"
id="email"
name="email"
value={formData.user.email}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.email ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.email && (
<p className="mt-1 text-sm text-red-600">{errors.email}</p>
)}
</div>
<div className="flex justify-end">
<button
type="button"
onClick={handleNext}
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
>
Next
</button>
</div>
</div>
);
case 2:
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Shipping address</h2>
<div>
<label htmlFor="street" className="block text-sm font-medium text-gray-700">
Street and number
</label>
<input
type="text"
id="street"
name="street"
value={formData.address.street}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.street ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.street && (
<p className="mt-1 text-sm text-red-600">{errors.street}</p>
)}
</div>
<div>
<label htmlFor="city" className="block text-sm font-medium text-gray-700">
City
</label>
<input
type="text"
id="city"
name="city"
value={formData.address.city}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.city ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.city && (
<p className="mt-1 text-sm text-red-600">{errors.city}</p>
)}
</div>
<div>
<label htmlFor="zipCode" className="block text-sm font-medium text-gray-700">
Postal code
</label>
<input
type="text"
id="zipCode"
name="zipCode"
value={formData.address.zipCode}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.zipCode ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.zipCode && (
<p className="mt-1 text-sm text-red-600">{errors.zipCode}</p>
)}
</div>
<div>
<label htmlFor="country" className="block text-sm font-medium text-gray-700">
Country
</label>
<input
type="text"
id="country"
name="country"
value={formData.address.country}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.country ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.country && (
<p className="mt-1 text-sm text-red-600">{errors.country}</p>
)}
</div>
<div className="flex justify-between">
<button
type="button"
onClick={handlePrevious}
className="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300"
>
Back
</button>
<button
type="button"
onClick={handleNext}
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
>
Next
</button>
</div>
</div>
);
case 3:
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Payment details</h2>
<div>
<label htmlFor="cardNumber" className="block text-sm font-medium text-gray-700">
Card number
</label>
<input
type="text"
id="cardNumber"
name="cardNumber"
value={formData.payment.cardNumber}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.cardNumber ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.cardNumber && (
<p className="mt-1 text-sm text-red-600">{errors.cardNumber}</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"
value={formData.payment.expiryDate}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.expiryDate ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.expiryDate && (
<p className="mt-1 text-sm text-red-600">{errors.expiryDate}</p>
)}
</div>
<div>
<label htmlFor="cvv" className="block text-sm font-medium text-gray-700">
CVV
</label>
<input
type="text"
id="cvv"
name="cvv"
value={formData.payment.cvv}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.cvv ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.cvv && (
<p className="mt-1 text-sm text-red-600">{errors.cvv}</p>
)}
</div>
</div>
<div className="flex justify-between">
<button
type="button"
onClick={handlePrevious}
className="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300"
>
Back
</button>
<button
type="submit"
onClick={handleSubmit}
className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600"
>
Place order
</button>
</div>
</div>
);
default:
return null;
}
}
return (
<div className="max-w-2xl mx-auto px-4 py-8">
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
step >= 1 ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'
}`}>
1
</div>
<div className={`h-1 w-12 ${step >= 2 ? 'bg-blue-500' : 'bg-gray-200'}`}></div>
</div>
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
step >= 2 ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'
}`}>
2
</div>
<div className={`h-1 w-12 ${step >= 3 ? 'bg-blue-500' : 'bg-gray-200'}`}></div>
</div>
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
step >= 3 ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'
}`}>
3
</div>
</div>
</div>
<div className="flex justify-between text-sm">
<span className={step >= 1 ? 'text-blue-500 font-medium' : ''}>Personal data</span>
<span className={step >= 2 ? 'text-blue-500 font-medium' : ''}>Address</span>
<span className={step >= 3 ? 'text-blue-500 font-medium' : ''}>Payment</span>
</div>
</div>
<form className="bg-white shadow-md rounded-lg p-6">
{renderStep()}
</form>
</div>
);
}Main features of this approach:
- A single component manages the entire process
- State contains all form data and the current step
- Switching between steps is done by changing state
- Validation is performed before moving to the next step
2. Per-step component approach
An alternative approach is to create separate components for each step, which improves code organization and reusability:
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
// Types for the form data
interface UserFormData {
firstName: string;
lastName: string;
email: string;
}
interface AddressFormData {
street: string;
city: string;
zipCode: string;
country: string;
}
interface PaymentFormData {
cardNumber: string;
expiryDate: string;
cvv: string;
}
export type FormData = {
user: UserFormData;
address: AddressFormData;
payment: PaymentFormData;
}
// Component for step 1: User data
interface UserFormProps {
data: UserFormData;
onSubmit: (data: UserFormData) => void;
}
function UserForm({ data, onSubmit }: UserFormProps) {
const [formData, setFormData] = useState(data);
const [errors, setErrors] = useState<Record<string, string>>({});
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
// Clearing errors
if (errors[name]) {
setErrors({ ...errors, [name]: '' });
}
}
function validate(): boolean {
const newErrors: Record<string, string> = {};
if (!formData.firstName.trim()) {
newErrors.firstName = 'Name is required';
}
if (!formData.lastName.trim()) {
newErrors.lastName = 'Last name is required';
}
if (!formData.email.trim()) {
newErrors.email = 'Email is required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(formData.email)) {
newErrors.email = 'Invalid email address format';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (validate()) {
onSubmit(formData);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<h2 className="text-xl font-semibold">Personal data</h2>
<div>
<label htmlFor="firstName" className="block text-sm font-medium text-gray-700">
First name
</label>
<input
type="text"
id="firstName"
name="firstName"
value={formData.firstName}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.firstName ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.firstName && (
<p className="mt-1 text-sm text-red-600">{errors.firstName}</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"
value={formData.lastName}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.lastName ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.lastName && (
<p className="mt-1 text-sm text-red-600">{errors.lastName}</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.email ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.email && (
<p className="mt-1 text-sm text-red-600">{errors.email}</p>
)}
</div>
<div className="flex justify-end">
<button
type="submit"
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
>
Next
</button>
</div>
</form>
);
}
// Component for step 2: Shipping address
interface AddressFormProps {
data: AddressFormData;
onSubmit: (data: AddressFormData) => void;
onBack: () => void;
}
function AddressForm({ data, onSubmit, onBack }: AddressFormProps) {
const [formData, setFormData] = useState(data);
const [errors, setErrors] = useState<Record<string, string>>({});
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
if (errors[name]) {
setErrors({ ...errors, [name]: '' });
}
}
function validate(): boolean {
const newErrors: Record<string, string> = {};
if (!formData.street.trim()) {
newErrors.street = 'Street is required';
}
if (!formData.city.trim()) {
newErrors.city = 'City is required';
}
if (!formData.zipCode.trim()) {
newErrors.zipCode = 'Postal code is required';
}
if (!formData.country.trim()) {
newErrors.country = 'Country is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (validate()) {
onSubmit(formData);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<h2 className="text-xl font-semibold">Shipping address</h2>
<div>
<label htmlFor="street" className="block text-sm font-medium text-gray-700">
Street and number
</label>
<input
type="text"
id="street"
name="street"
value={formData.street}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.street ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.street && (
<p className="mt-1 text-sm text-red-600">{errors.street}</p>
)}
</div>
<div>
<label htmlFor="city" className="block text-sm font-medium text-gray-700">
City
</label>
<input
type="text"
id="city"
name="city"
value={formData.city}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.city ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.city && (
<p className="mt-1 text-sm text-red-600">{errors.city}</p>
)}
</div>
<div>
<label htmlFor="zipCode" className="block text-sm font-medium text-gray-700">
Postal code
</label>
<input
type="text"
id="zipCode"
name="zipCode"
value={formData.zipCode}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.zipCode ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.zipCode && (
<p className="mt-1 text-sm text-red-600">{errors.zipCode}</p>
)}
</div>
<div>
<label htmlFor="country" className="block text-sm font-medium text-gray-700">
Country
</label>
<input
type="text"
id="country"
name="country"
value={formData.country}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.country ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.country && (
<p className="mt-1 text-sm text-red-600">{errors.country}</p>
)}
</div>
<div className="flex justify-between">
<button
type="button"
onClick={onBack}
className="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300"
>
Back
</button>
<button
type="submit"
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
>
Next
</button>
</div>
</form>
);
}
// Component for step 3: Payment
interface PaymentFormProps {
data: PaymentFormData;
onSubmit: (data: PaymentFormData) => void;
onBack: () => void;
}
function PaymentForm({ data, onSubmit, onBack }: PaymentFormProps) {
const [formData, setFormData] = useState(data);
const [errors, setErrors] = useState<Record<string, string>>({});
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
if (errors[name]) {
setErrors({ ...errors, [name]: '' });
}
}
function validate(): boolean {
const newErrors: Record<string, string> = {};
if (!formData.cardNumber.trim()) {
newErrors.cardNumber = 'Card number is required';
} else if (!/^\d{16}$/.test(formData.cardNumber.replace(/\s/g, ''))) {
newErrors.cardNumber = 'Invalid card number';
}
if (!formData.expiryDate.trim()) {
newErrors.expiryDate = 'Expiry date is required';
}
if (!formData.cvv.trim()) {
newErrors.cvv = 'CVV code is required';
} else if (!/^\d{3,4}$/.test(formData.cvv)) {
newErrors.cvv = 'Invalid CVV code';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (validate()) {
onSubmit(formData);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<h2 className="text-xl font-semibold">Payment details</h2>
<div>
<label htmlFor="cardNumber" className="block text-sm font-medium text-gray-700">
Card number
</label>
<input
type="text"
id="cardNumber"
name="cardNumber"
value={formData.cardNumber}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.cardNumber ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.cardNumber && (
<p className="mt-1 text-sm text-red-600">{errors.cardNumber}</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"
value={formData.expiryDate}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.expiryDate ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.expiryDate && (
<p className="mt-1 text-sm text-red-600">{errors.expiryDate}</p>
)}
</div>
<div>
<label htmlFor="cvv" className="block text-sm font-medium text-gray-700">
CVV
</label>
<input
type="text"
id="cvv"
name="cvv"
value={formData.cvv}
onChange={handleChange}
className={`mt-1 block w-full rounded-md border ${
errors.cvv ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.cvv && (
<p className="mt-1 text-sm text-red-600">{errors.cvv}</p>
)}
</div>
</div>
<div className="flex justify-between">
<button
type="button"
onClick={onBack}
className="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300"
>
Back
</button>
<button
type="submit"
className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600"
>
Place order
</button>
</div>
</form>
);
}
// Confirmation component
interface ConfirmationProps {
data: FormData;
onEdit: (step: number) => void;
}
function Confirmation({ data, onEdit }: ConfirmationProps) {
const router = useRouter();
async function handleConfirm() {
try {
// Simulate API submission
console.log('Submitting order:', data);
// Example API call (in a real application)
// await fetch('/api/checkout', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(data)
// });
// Redirect to success page
// router.push('/checkout/success');
// In this example we just alert success
alert('Order has been placed successfully!');
} catch (error) {
console.error('Error placing order:', error);
alert('An error occurred while placing the order. Try again.');
}
}
return (
<div className="space-y-6">
<h2 className="text-xl font-semibold">Order confirmation</h2>
<div className="border border-gray-200 rounded-lg p-4 space-y-4">
<div>
<h3 className="font-medium text-gray-700 mb-2">Personal data</h3>
<div className="bg-gray-50 p-3 rounded">
<p>{data.user.firstName} {data.user.lastName}</p>
<p>{data.user.email}</p>
</div>
<button
type="button"
onClick={() => onEdit(1)}
className="text-sm text-blue-500 mt-1"
>
Edit
</button>
</div>
<div>
<h3 className="font-medium text-gray-700 mb-2">Shipping address</h3>
<div className="bg-gray-50 p-3 rounded">
<p>{data.address.street}</p>
<p>{data.address.zipCode} {data.address.city}</p>
<p>{data.address.country}</p>
</div>
<button
type="button"
onClick={() => onEdit(2)}
className="text-sm text-blue-500 mt-1"
>
Edit
</button>
</div>
<div>
<h3 className="font-medium text-gray-700 mb-2">Payment method</h3>
<div className="bg-gray-50 p-3 rounded">
<p>Card: **** **** **** {data.payment.cardNumber.slice(-4)}</p>
<p>Valid until: {data.payment.expiryDate}</p>
</div>
<button
type="button"
onClick={() => onEdit(3)}
className="text-sm text-blue-500 mt-1"
>
Edit
</button>
</div>
</div>
<div className="flex justify-center">
<button
type="button"
onClick={handleConfirm}
className="px-6 py-2 bg-green-500 text-white rounded-md hover:bg-green-600"
>
Confirm and place order
</button>
</div>
</div>
);
}
// Main multi-step form component
export default function MultiStepCheckout() {
const [step, setStep] = useState(1);
const [formData, setFormData] = useState<FormData>({
user: {
firstName: '',
lastName: '',
email: ''
},
address: {
street: '',
city: '',
zipCode: '',
country: ''
},
payment: {
cardNumber: '',
expiryDate: '',
cvv: ''
}
});
function handleUserSubmit(userData: UserFormData) {
setFormData({ ...formData, user: userData });
setStep(2);
}
function handleAddressSubmit(addressData: AddressFormData) {
setFormData({ ...formData, address: addressData });
setStep(3);
}
function handlePaymentSubmit(paymentData: PaymentFormData) {
setFormData({ ...formData, payment: paymentData });
setStep(4);
}
function renderProgressBar() {
return (
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
{[1, 2, 3, 4].map((num) => (
<div key={num} className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
step >= num ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'
}`}>
{num}
</div>
{num < 4 && (
<div className={`h-1 w-12 ${step > num ? 'bg-blue-500' : 'bg-gray-200'}`}></div>
)}
</div>
))}
</div>
<div className="flex justify-between text-sm">
<span className={step >= 1 ? 'text-blue-500 font-medium' : ''}>Personal data</span>
<span className={step >= 2 ? 'text-blue-500 font-medium' : ''}>Address</span>
<span className={step >= 3 ? 'text-blue-500 font-medium' : ''}>Payment</span>
<span className={step >= 4 ? 'text-blue-500 font-medium' : ''}>Confirmation</span>
</div>
</div>
);
}
function renderStep() {
switch (step) {
case 1:
return <UserForm data={formData.user} onSubmit={handleUserSubmit} />;
case 2:
return (
<AddressForm
data={formData.address}
onSubmit={handleAddressSubmit}
onBack={() => setStep(1)}
/>
);
case 3:
return (
<PaymentForm
data={formData.payment}
onSubmit={handlePaymentSubmit}
onBack={() => setStep(2)}
/>
);
case 4:
return <Confirmation data={formData} onEdit={setStep} />;
default:
return null;
}
}
return (
<div className="max-w-2xl mx-auto px-4 py-8">
{renderProgressBar()}
<div className="bg-white shadow-md rounded-lg p-6">
{renderStep()}
</div>
</div>
);
}Advantages of this approach:
- Better code organization
- Each step is a separate, independent component
- Easier validation for each step
- Components can be reused in other places
- Easier testing of individual stages
3. Multi-step forms with Server Actions in Next.js
For Next.js applications we can use Server Actions to handle form data:
// app/checkout/page.tsx
'use client';
import { useState } from 'react';
import { submitUserData, submitAddressData, submitPaymentData, completeOrder } from './actions';
// Similar types and form components as in the previous example
//
export default function CheckoutPage() {
const [step, setStep] = useState(1);
const [userId, setUserId] = useState<string | null>(null);
const [formData, setFormData] = useState({
user: { /* user data */ },
address: { /* address */ },
payment: { /* payment */ }
});
async function handleUserSubmit(userData: UserFormData) {
try {
// Save user data using Server Action
const result = await submitUserData(userData);
if (result.success) {
setUserId(result.userId);
setFormData({ ...formData, user: userData });
setStep(2);
} else {
// Error handling
alert(result.error || 'An error occurred. Try again.');
}
} catch (error) {
console.error('Error submitting user data:', error);
alert('An unexpected error occurred. Try again.');
}
}
async function handleAddressSubmit(addressData: AddressFormData) {
if (!userId) return;
try {
const result = await submitAddressData(userId, addressData);
if (result.success) {
setFormData({ ...formData, address: addressData });
setStep(3);
} else {
alert(result.error || 'An error occurred. Try again.');
}
} catch (error) {
console.error('Error submitting address data:', error);
alert('An unexpected error occurred. Try again.');
}
}
// Similar functions for the remaining steps
//
// Render form components for each step, similar to before
//
}Here's a sample Server Actions implementation:
// app/checkout/actions.ts
'use server';
import { z } from 'zod';
// Validation schemas for the forms
const UserSchema = 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' })
});
const AddressSchema = z.object({
street: z.string().min(1, { message: 'Street is required' }),
city: z.string().min(1, { message: 'City is required' }),
zipCode: z.string().min(1, { message: 'Postal code is required' }),
country: z.string().min(1, { message: 'Country is required' })
});
// Server response types
type ServerResponse<T> =
| { success: true; data: T }
| { success: false; error: string };
export async function submitUserData(formData: unknown): Promise<ServerResponse<{ userId: string }>> {
try {
// Validate data
const validatedData = UserSchema.safeParse(formData);
if (!validatedData.success) {
return {
success: false,
error: validatedData.error.errors[0]?.message || 'Invalid data'
};
}
// In a real application: save data to the database
// const user = await db.user.create({ data: validatedData.data });
// Simulating user creation
console.log('User data saved:', validatedData.data);
return {
success: true,
data: { userId: 'user_123' }
};
} catch (error) {
console.error('Server error when submitting user data:', error);
return {
success: false,
error: 'An error occurred while processing data'
};
}
}
export async function submitAddressData(
userId: string,
formData: unknown
): Promise<ServerResponse<{ addressId: string }>> {
try {
// Validate data
const validatedData = AddressSchema.safeParse(formData);
if (!validatedData.success) {
return {
success: false,
error: validatedData.error.errors[0]?.message || 'Invalid address data'
};
}
// In a real application: save the address to the database
// const address = await db.address.create({
// data: { ...validatedData.data, userId }
// });
// Simulating address saving
console.log('Address saved for user', userId, ':', validatedData.data);
return {
success: true,
data: { addressId: 'addr_456' }
};
} catch (error) {
console.error('Server error when submitting address data:', error);
return {
success: false,
error: 'An error occurred while processing the address'
};
}
}
// Similar functions for payment and order finalization
//Advantages of this approach:
- Data validation and processing on the server
- Ability to incrementally save data to the database
- Better protection for sensitive data (e.g., payment details)
- Support for progressive enhancement
State management in multi-step forms
For more complex forms, it's worth considering libraries for form state management:
State management with Formik or React Hook Form
// Example with React Hook Form
import { useForm, FormProvider, useFormContext } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// Validation schema
const CheckoutSchema = z.object({
user: z.object({
firstName: z.string().min(1, 'Name is required'),
lastName: z.string().min(1, 'Last name is required'),
email: z.string().email('Invalid email address')
}),
address: z.object({
street: z.string().min(1, 'Street is required'),
city: z.string().min(1, 'City is required'),
zipCode: z.string().min(1, 'Postal code is required'),
country: z.string().min(1, 'Country is required')
}),
payment: z.object({
cardNumber: z.string().refine(val => /^\d{16}$/.test(val.replace(/\s/g, '')), {
message: 'Invalid card number'
}),
expiryDate: z.string().min(1, 'Expiry date is required'),
cvv: z.string().refine(val => /^\d{3,4}$/.test(val), {
message: 'Invalid CVV code'
})
})
});
type CheckoutData = z.infer<typeof CheckoutSchema>;
function UserFormStep() {
const { register, formState: { errors } } = useFormContext<CheckoutData>();
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Personal data</h2>
<div>
<label htmlFor="firstName" className="block text-sm font-medium">First name</label>
<input
id="firstName"
{...register('user.firstName')}
className={`mt-1 block w-full rounded-md border ${
errors.user?.firstName ? 'border-red-500' : 'border-gray-300'
} px-3 py-2`}
/>
{errors.user?.firstName && (
<p className="mt-1 text-sm text-red-600">{errors.user.firstName.message}</p>
)}
</div>
{/* Remaining fields... */}
</div>
);
}
// Similarly define the remaining form steps
//
export default function CheckoutForm() {
const [step, setStep] = useState(1);
const methods = useForm<CheckoutData>({
resolver: zodResolver(CheckoutSchema),
mode: 'onBlur',
defaultValues: {
user: { firstName: '', lastName: '', email: '' },
address: { street: '', city: '', zipCode: '', country: '' },
payment: { cardNumber: '', expiryDate: '', cvv: '' }
}
});
function onSubmit(data: CheckoutData) {
console.log('Submitting data:', data);
// Logic for submitting data to the API
}
const nextStep = () => {
if (step < 3) {
setStep(step + 1);
} else {
methods.handleSubmit(onSubmit)();
}
};
const prevStep = () => setStep(step - 1);
return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
{/* Progress bar */}
{/* Render the appropriate step */}
{step === 1 && <UserFormStep />}
{step === 2 && <AddressFormStep />}
{step === 3 && <PaymentFormStep />}
{/* Navigation buttons */}
<div className="mt-6 flex justify-between">
{step > 1 && (
<button
type="button"
onClick={prevStep}
className="px-4 py-2 bg-gray-200 text-gray-800 rounded-md"
>
Back
</button>
)}
<button
type="button"
onClick={nextStep}
className={`px-4 py-2 ${
step === 3 ? 'bg-green-500 hover:bg-green-600' : 'bg-blue-500 hover:bg-blue-600'
} text-white rounded-md`}
>
{step === 3 ? 'Place order' : 'Next'}
</button>
</div>
</form>
</FormProvider>
);
}State management using React Context
For very complex forms, it can be beneficial to use the React Context API:
// context/CheckoutContext.tsx
import { createContext, useContext, useReducer, ReactNode } from 'react';
// Form data types
//
// Form state
interface CheckoutState {
step: number;
user: UserFormData;
address: AddressFormData;
payment: PaymentFormData;
errors: Record<string, string>;
}
// Action types
type CheckoutAction =
| { type: 'SET_STEP'; payload: number }
| { type: 'UPDATE_USER'; payload: Partial<UserFormData> }
| { type: 'UPDATE_ADDRESS'; payload: Partial<AddressFormData> }
| { type: 'UPDATE_PAYMENT'; payload: Partial<PaymentFormData> }
| { type: 'SET_ERRORS'; payload: Record<string, string> }
| { type: 'CLEAR_ERRORS' };
// Initial state
const initialState: CheckoutState = {
step: 1,
user: { firstName: '', lastName: '', email: '' },
address: { street: '', city: '', zipCode: '', country: '' },
payment: { cardNumber: '', expiryDate: '', cvv: '' },
errors: {}
};
// Reducer
function checkoutReducer(state: CheckoutState, action: CheckoutAction): CheckoutState {
switch (action.type) {
case 'SET_STEP':
return { ...state, step: action.payload };
case 'UPDATE_USER':
return { ...state, user: { ...state.user, ...action.payload } };
case 'UPDATE_ADDRESS':
return { ...state, address: { ...state.address, ...action.payload } };
case 'UPDATE_PAYMENT':
return { ...state, payment: { ...state.payment, ...action.payload } };
case 'SET_ERRORS':
return { ...state, errors: action.payload };
case 'CLEAR_ERRORS':
return { ...state, errors: {} };
default:
return state;
}
}
// Context type
interface CheckoutContextType {
state: CheckoutState;
nextStep: () => void;
prevStep: () => void;
updateUser: (data: Partial<UserFormData>) => void;
updateAddress: (data: Partial<AddressFormData>) => void;
updatePayment: (data: Partial<PaymentFormData>) => void;
validateStep: (step: number) => boolean;
submitOrder: () => Promise<void>;
}
// Context
const CheckoutContext = createContext<CheckoutContextType | undefined>(undefined);
// Provider
export function CheckoutProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(checkoutReducer, initialState);
// Helper functions
const nextStep = () => {
if (validateStep(state.step)) {
dispatch({ type: 'SET_STEP', payload: state.step + 1 });
}
};
const prevStep = () => {
dispatch({ type: 'SET_STEP', payload: state.step - 1 });
};
const updateUser = (data: Partial<UserFormData>) => {
dispatch({ type: 'UPDATE_USER', payload: data });
};
const updateAddress = (data: Partial<AddressFormData>) => {
dispatch({ type: 'UPDATE_ADDRESS', payload: data });
};
const updatePayment = (data: Partial<PaymentFormData>) => {
dispatch({ type: 'UPDATE_PAYMENT', payload: data });
};
// Step validation
const validateStep = (step: number): boolean => {
// Validation logic...
return true; // Simplified for the example
};
// Submitting the order
const submitOrder = async () => {
if (validateStep(state.step)) {
try {
// Data submission logic
console.log('Submitting data:', state);
} catch (error) {
console.error('Error submitting order:', error);
}
}
};
return (
<CheckoutContext.Provider
value={{
state,
nextStep,
prevStep,
updateUser,
updateAddress,
updatePayment,
validateStep,
submitOrder
}}
>
{children}
</CheckoutContext.Provider>
);
}
// Hook to use the context
export function useCheckout() {
const context = useContext(CheckoutContext);
if (context === undefined) {
throw new Error('useCheckout must be used within a CheckoutProvider');
}
return context;
}Advanced techniques for multi-step forms
1. Conditional form paths
Sometimes we want users to go through different form paths depending on their choices:
// Sample implementation of conditional paths
function determineNextStep(currentStep: number, formData: FormData): number {
if (currentStep === 1) {
// If user chose shipping to a different address, add the shipping address step
if (formData.shippingDifferent) {
return 2; // Shipping address step
} else {
return 3; // Skip shipping address step, go to payment
}
}
if (currentStep === 3) {
// If user chose bank transfer payment, skip the card details step
if (formData.paymentMethod === 'bankTransfer') {
return 5; // Go to summary
} else {
return 4; // Card details step
}
}
// Default transition to next step
return currentStep + 1;
}
// Usage in a component
function handleNext() {
const isValid = validateCurrentStep();
if (isValid) {
const nextStep = determineNextStep(step, formData);
setStep(nextStep);
}
}2. Saving and restoring form state
For long forms, it's worth allowing progress to be saved:
'use client';
import { useState, useEffect } from 'react';
// Save form state
function saveFormState(data: FormData) {
localStorage.setItem('checkout_form', JSON.stringify(data));
localStorage.setItem('checkout_timestamp', Date.now().toString());
}
// Restore form state
function getSavedFormState(): FormData | null {
const savedData = localStorage.getItem('checkout_form');
const timestamp = localStorage.getItem('checkout_timestamp');
if (!savedData || !timestamp) {
return null;
}
// Check if saved data is not too old (e.g., 24 hours)
const savedTime = parseInt(timestamp, 10);
const now = Date.now();
const oneDayMs = 24 * 60 * 60 * 1000;
if (now - savedTime > oneDayMs) {
// Data is too old, remove it
localStorage.removeItem('checkout_form');
localStorage.removeItem('checkout_timestamp');
return null;
}
try {
return JSON.parse(savedData) as FormData;
} catch (e) {
return null;
}
}
export default function CheckoutForm() {
const [formData, setFormData] = useState<FormData>({
// Default form state
});
const [step, setStep] = useState(1);
const [hasRestoredState, setHasRestoredState] = useState(false);
// Attempt to restore form state on first render
useEffect(() => {
if (!hasRestoredState) {
const savedState = getSavedFormState();
if (savedState) {
setFormData(savedState);
setHasRestoredState(true);
// Optionally, ask the user if they want to continue from where they left off
const wishToContinue = window.confirm(
'An incomplete form from a previous session was found. Do you want to continue from where you left off?'
);
if (wishToContinue) {
// We can determine which step the user ended on
// e.g., based on which data is already filled in
if (savedState.payment.cardNumber) {
setStep(3);
} else if (savedState.address.street) {
setStep(2);
} else {
setStep(1);
}
} else {
// User doesn't want to continue, clear saved data
localStorage.removeItem('checkout_form');
localStorage.removeItem('checkout_timestamp');
setFormData({
// Reset to default state
});
}
}
setHasRestoredState(true);
}
}, [hasRestoredState]);
// Save form state on changes
useEffect(() => {
if (hasRestoredState) {
saveFormState(formData);
}
}, [formData, hasRestoredState]);
// Rest of the component...
}3. Dynamically adding and removing form fields
In some multi-step forms, users may need to dynamically add or remove elements:
'use client';
import { useState } from 'react';
interface Item {
id: string;
name: string;
quantity: number;
}
function OrderItemsStep() {
const [items, setItems] = useState<Item[]>([
{ id: '1', name: '', quantity: 1 }
]);
const addItem = () => {
const newId = (parseInt(items[items.length - 1].id) + 1).toString();
setItems([...items, { id: newId, name: '', quantity: 1 }]);
};
const removeItem = (id: string) => {
// Don't remove the last item
if (items.length <= 1) return;
setItems(items.filter(item => item.id !== id));
};
const updateItem = (id: string, field: keyof Item, value: string | number) => {
setItems(items.map(item =>
item.id === id ? { ...item, [field]: value } : item
));
};
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Order items</h2>
{items.map(item => (
<div key={item.id} className="flex items-center space-x-4 p-4 border rounded-md">
<div className="grow">
<label htmlFor={`item-name-${item.id}`} className="block text-sm font-medium">
Product name
</label>
<input
id={`item-name-${item.id}`}
type="text"
value={item.name}
onChange={(e) => updateItem(item.id, 'name', e.target.value)}
className="mt-1 block w-full rounded-md border-gray-300 px-3 py-2"
/>
</div>
<div className="w-24">
<label htmlFor={`item-qty-${item.id}`} className="block text-sm font-medium">
Quantity
</label>
<input
id={`item-qty-${item.id}`}
type="number"
min="1"
value={item.quantity}
onChange={(e) => updateItem(item.id, 'quantity', parseInt(e.target.value))}
className="mt-1 block w-full rounded-md border-gray-300 px-3 py-2"
/>
</div>
<button
type="button"
onClick={() => removeItem(item.id)}
className="mt-6 px-2 py-2 bg-red-100 text-red-600 rounded-md hover:bg-red-200"
aria-label="Remove item"
>
×
</button>
</div>
))}
<button
type="button"
onClick={addItem}
className="w-full mt-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200"
>
+ Add more products
</button>
</div>
);
}Good practices for multi-step forms
Show progress - indicate to the user where they are in the process (progress bar, step numbering)
Preserve data - users should not lose entered data when the page is refreshed or accidentally closed
Enable navigation between steps - allow users to return to previous steps and edit data
Validate each step - check data correctness before moving to the next step
Provide clear error messages - inform the user exactly what went wrong
Allow saving and returning later - especially for long forms
Adapt steps to the device - on smaller screens consider even smaller steps
Provide a summary before final submission - give users an overview of all entered data
Handle browser back/forward - adapt the application to work with the browser's back/forward button
Test various scenarios - make sure the form works correctly both for standard filling and in scenarios such as:
- Going back to previous steps
- Refreshing the page
- Attempting to submit incomplete data
- Losing internet connection
Drizzle ORM - a lightweight alternative to Prisma
In Quantum Metropolis of the year 2150, where every processor cycle matters, developers often look for tools that are both powerful and lightweight. Drizzle ORM is a modern alternative to Prisma that offers type safety while staying close to pure SQL.
Drizzle vs Prisma - comparison
Both Drizzle and Prisma are type-safe ORMs for TypeScript, but they differ in philosophy and approach:
| Aspect | Drizzle ORM | Prisma |
|---|---|---|
| Philosophy | SQL-like, closer to the metal | Abstraction-first, friendly API |
| Size | ~20KB | ~600KB+ |
| Migrations | SQL or TypeScript | Custom DSL language |
| Queries | SQL-like | Custom API |
| Performance | Very fast | Good |
| Learning curve | Gentle for SQL users | Gentle for beginners |
| Type safety | Full | Full |
| Edge Runtime | Native support | Requires Data Proxy |
Why Drizzle is lighter and closer to SQL
Drizzle is a "thin TypeScript layer" over SQL, which means:
- Minimal abstraction - queries look like SQL, so they are easy to optimize
- Small bundle size - Drizzle code is compact
- Zero runtime overhead - all types are removed during compilation
- Full control - you can use raw SQL when you need to
// Drizzle - looks like SQL
const result = await db
.select()
.from(users)
.where(eq(users.email, 'user@example.com'))
.limit(1);
// Prisma - more abstract
const result = await prisma.user.findUnique({
where: { email: 'user@example.com' }
});Type-safe queries with Drizzle
Drizzle offers full TypeScript support, catching errors while you are writing code:
Schema definition
// db/schema.ts
import { pgTable, serial, text, varchar, timestamp, integer, boolean } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// Users table
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 255 }).notNull(),
email: varchar('email', { length: 255 }).notNull().unique(),
password: text('password').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull()
});
// Posts table
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: varchar('title', { length: 255 }).notNull(),
content: text('content').notNull(),
published: boolean('published').default(false).notNull(),
authorId: integer('author_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull()
});
// Comments table
export const comments = pgTable('comments', {
id: serial('id').primaryKey(),
content: text('content').notNull(),
postId: integer('post_id')
.notNull()
.references(() => posts.id, { onDelete: 'cascade' }),
authorId: integer('author_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: timestamp('created_at').defaultNow().notNull()
});
// Relations between tables
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
comments: many(comments)
}));
export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id]
}),
comments: many(comments)
}));
export const commentsRelations = relations(comments, ({ one }) => ({
post: one(posts, {
fields: [comments.postId],
references: [posts.id]
}),
author: one(users, {
fields: [comments.authorId],
references: [users.id]
})
}));
// TypeScript types generated automatically
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Post = typeof posts.$inferSelect;
export type NewPost = typeof posts.$inferInsert;
export type Comment = typeof comments.$inferSelect;
export type NewComment = typeof comments.$inferInsert;Connection configuration
// db/index.ts
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
// PostgreSQL client
const connectionString = process.env.DATABASE_URL!;
const client = postgres(connectionString);
// Drizzle instance
export const db = drizzle(client, { schema });
// For Edge Runtime (Vercel, Cloudflare Workers)
// import { drizzle } from 'drizzle-orm/vercel-postgres';
// import { sql } from '@vercel/postgres';
// export const db = drizzle(sql, { schema });Type-safe queries
// app/actions/users.ts
'use server';
import { db } from '@/db';
import { users, posts } from '@/db/schema';
import { eq, and, or, like, desc, count } from 'drizzle-orm';
// SELECT - fetching data
export async function getUser(id: number) {
const [user] = await db
.select()
.from(users)
.where(eq(users.id, id))
.limit(1);
return user;
}
// SELECT with multiple conditions
export async function searchUsers(query: string) {
return await db
.select({
id: users.id,
name: users.name,
email: users.email
})
.from(users)
.where(
or(
like(users.name, `%${query}%`),
like(users.email, `%${query}%`)
)
)
.limit(10);
}
// INSERT - creating a user
export async function createUser(data: {
name: string;
email: string;
password: string;
}) {
const [newUser] = await db
.insert(users)
.values(data)
.returning(); // PostgreSQL specific
return newUser;
}
// UPDATE - updating a user
export async function updateUser(
id: number,
data: Partial<{ name: string; email: string }>
) {
const [updated] = await db
.update(users)
.set({
...data,
updatedAt: new Date()
})
.where(eq(users.id, id))
.returning();
return updated;
}
// DELETE - deleting a user
export async function deleteUser(id: number) {
await db
.delete(users)
.where(eq(users.id, id));
}
// JOIN - fetching a user with their posts
export async function getUserWithPosts(userId: number) {
return await db.query.users.findFirst({
where: eq(users.id, userId),
with: {
posts: {
orderBy: [desc(posts.createdAt)],
limit: 10
}
}
});
}
// Aggregations
export async function getPostsCount(userId: number) {
const [result] = await db
.select({ count: count() })
.from(posts)
.where(eq(posts.authorId, userId));
return result.count;
}
// Transactions
export async function createUserWithPost(
userData: { name: string; email: string; password: string },
postData: { title: string; content: string }
) {
return await db.transaction(async (tx) => {
// Create user
const [user] = await tx
.insert(users)
.values(userData)
.returning();
// Create a post for this user
const [post] = await tx
.insert(posts)
.values({
...postData,
authorId: user.id,
published: false
})
.returning();
return { user, post };
});
}Advanced queries
Relational queries (Relational Queries API)
// The simplest way to do JOINs
export async function getPostsWithAuthors() {
return await db.query.posts.findMany({
with: {
author: true,
comments: {
with: {
author: true
}
}
},
orderBy: [desc(posts.createdAt)],
limit: 20
});
}
// Partial select with relations
export async function getPostsPartial() {
return await db.query.posts.findMany({
columns: {
id: true,
title: true,
createdAt: true
},
with: {
author: {
columns: {
id: true,
name: true
}
}
}
});
}
// Filtering within relations
export async function getPublishedPostsWithComments() {
return await db.query.posts.findMany({
where: eq(posts.published, true),
with: {
comments: {
where: (comments, { gte }) =>
gte(comments.createdAt, new Date('2024-01-01')),
limit: 5,
orderBy: [desc(comments.createdAt)]
}
}
});
}Raw SQL when you need it
import { sql } from 'drizzle-orm';
// Raw SQL for advanced queries
export async function complexAnalytics() {
const result = await db.execute(sql`
SELECT
u.id,
u.name,
COUNT(DISTINCT p.id) as posts_count,
COUNT(DISTINCT c.id) as comments_count,
MAX(p.created_at) as last_post_date
FROM users u
LEFT JOIN posts p ON p.author_id = u.id
LEFT JOIN comments c ON c.author_id = u.id
WHERE u.created_at > NOW() - INTERVAL '30 days'
GROUP BY u.id, u.name
ORDER BY posts_count DESC
LIMIT 10
`);
return result.rows;
}
// Combining type-safe queries with raw SQL
export async function hybridQuery(minPosts: number) {
return await db
.select({
userId: users.id,
userName: users.name,
postsCount: sql<number>`COUNT(${posts.id})`
})
.from(users)
.leftJoin(posts, eq(posts.authorId, users.id))
.groupBy(users.id)
.having(sql`COUNT(${posts.id}) > ${minPosts}`);
}Migrations in Drizzle
Drizzle offers two ways to handle migrations:
1. Automatic SQL generation
// drizzle.config.ts
import type { Config } from 'drizzle-kit';
export default {
schema: './db/schema.ts',
out: './drizzle',
driver: 'pg',
dbCredentials: {
connectionString: process.env.DATABASE_URL!
}
} satisfies Config;# Generate migrations
npx drizzle-kit generate:pg
# Run migrations
npx drizzle-kit push:pg
# Or using a custom script
# db/migrate.ts
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
const db = drizzle(sql);
await migrate(db, { migrationsFolder: './drizzle' });
await sql.end();2. Manual SQL migrations
-- drizzle/0001_initial.sql
CREATE TABLE IF NOT EXISTS "users" (
"id" serial PRIMARY KEY NOT NULL,
"name" varchar(255) NOT NULL,
"email" varchar(255) NOT NULL,
"password" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "users_email_unique" UNIQUE("email")
);
CREATE TABLE IF NOT EXISTS "posts" (
"id" serial PRIMARY KEY NOT NULL,
"title" varchar(255) NOT NULL,
"content" text NOT NULL,
"published" boolean DEFAULT false NOT NULL,
"author_id" integer NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "posts_author_id_users_id_fk"
FOREIGN KEY ("author_id") REFERENCES "users"("id")
ON DELETE cascade
);Integration with the Next.js App Router
// app/users/[id]/page.tsx
import { db } from '@/db';
import { users, posts } from '@/db/schema';
import { eq, desc } from 'drizzle-orm';
export default async function UserPage({
params
}: {
params: Promise<{ id: string }>
}) {
const userId = parseInt((await params).id);
// Query executed in a Server Component
const user = await db.query.users.findFirst({
where: eq(users.id, userId),
with: {
posts: {
orderBy: [desc(posts.createdAt)],
limit: 5
}
}
});
if (!user) {
return <div>User not found</div>;
}
return (
<div className="p-8">
<h1 className="text-3xl font-bold mb-4">{user.name}</h1>
<p className="text-gray-600 mb-8">{user.email}</p>
<h2 className="text-2xl font-semibold mb-4">Posts</h2>
<div className="space-y-4">
{user.posts.map(post => (
<article key={post.id} className="border p-4 rounded-lg">
<h3 className="text-xl font-bold">{post.title}</h3>
<p className="text-gray-600 mt-2">{post.content}</p>
<time className="text-sm text-gray-400 mt-2 block">
{post.createdAt.toLocaleDateString()}
</time>
</article>
))}
</div>
</div>
);
}
// app/actions/posts.ts
'use server';
import { db } from '@/db';
import { posts } from '@/db/schema';
import { revalidatePath } from 'next/cache';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
const authorId = parseInt(formData.get('authorId') as string);
const [newPost] = await db
.insert(posts)
.values({
title,
content,
authorId,
published: false
})
.returning();
revalidatePath(`/users/${authorId}`);
return { success: true, post: newPost };
}Drizzle vs Prisma - when to choose which?
Choose Drizzle when:
- You know SQL well and want full control
- You care about a small bundle size
- You are building edge applications
- You need maximum performance
- You prefer minimalism and simplicity
Choose Prisma when:
- You are a beginner or intermediate developer
- You need excellent documentation and ecosystem
- You want abstraction and don't want to worry about SQL
- You use Prisma Studio for data management
- Your team is larger and needs consistent conventions
Practical Application
In Quantum Metropolis, where applications have to be both powerful and lightweight, Drizzle offers an excellent alternative. Its closeness to SQL means experienced developers can easily optimize queries, while full TypeScript support provides type safety at every step.
// Real-world example: Dashboard with analytics
export async function getDashboardStats(userId: number) {
// Everything type-safe, SQL-like, fast
const stats = await db
.select({
totalPosts: count(posts.id),
publishedPosts: sql<number>`
COUNT(CASE WHEN ${posts.published} = true THEN 1 END)
`,
draftPosts: sql<number>`
COUNT(CASE WHEN ${posts.published} = false THEN 1 END)
`,
totalComments: count(comments.id)
})
.from(users)
.leftJoin(posts, eq(posts.authorId, users.id))
.leftJoin(comments, eq(comments.postId, posts.id))
.where(eq(users.id, userId))
.groupBy(users.id);
return stats[0];
}Summary
Multi-step forms are a powerful tool for collecting complex data from users in a friendly and organized way. There are many strategies for implementing them, from simple component-state-based approaches, through modular approaches with separate components for each step, to advanced solutions that leverage React context and form management libraries.
In React and Next.js, we have flexible options for implementing such forms, with additional benefits offered by Server Actions in Next.js for progressive enhancement and data security.
The key to success is choosing an approach appropriate to the form's complexity and the application's needs, while providing users with a smooth and frictionless experience.
Code for this lesson: App.tsx
import React, { useState } from 'react';
type Step1Data = { firstName: string; lastName: string; email: string };
type Step2Data = { company: string; role: string; experience: string };
type Step3Data = { plan: string; newsletter: boolean };
type AllData = Step1Data & Step2Data & Step3Data;
const TOTAL_STEPS = 3;
function StepIndicator({ current, total }: { current: number; total: number }) {
return (
<div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
{Array.from({ length: total }, (_, i) => (
<React.Fragment key={i}>
<div style={{
width: 32, height: 32, borderRadius: '50%', display: 'flex',
alignItems: 'center', justifyContent: 'center', fontWeight: 'bold',
fontSize: 13, fontFamily: 'monospace',
background: i + 1 < current ? '#4caf50' : i + 1 === current ? '#1a2744' : '#0d1117',
color: i + 1 < current ? '#fff' : i + 1 === current ? '#64ffda' : '#555',
border: i + 1 === current ? '2px solid #64ffda' : '2px solid transparent',
}}>
{i + 1 < current ? 'β' : i + 1}
</div>
{i < total - 1 && (
<div style={{ flex: 1, height: 2, background: i + 1 < current ? '#4caf50' : '#333', margin: '0 6px' }} />
)}
</React.Fragment>
))}
</div>
);
}
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', marginBottom: 12
};
function Step1({ data, onChange }: { data: Step1Data; onChange: (d: Partial<Step1Data>) => void }) {
return (
<div>
<h3 style={{ color: '#64ffda', margin: '0 0 12px' }}>Step 1: Personal information</h3>
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>First name *</label>
<input value={data.firstName} onChange={e => onChange({ firstName: e.target.value })} placeholder="Jan" style={inputStyle} />
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Last name *</label>
<input value={data.lastName} onChange={e => onChange({ lastName: e.target.value })} placeholder="Kowalski" style={inputStyle} />
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Email *</label>
<input type="email" value={data.email} onChange={e => onChange({ email: e.target.value })} placeholder="jan@example.com" style={inputStyle} />
</div>
);
}
function Step2({ data, onChange }: { data: Step2Data; onChange: (d: Partial<Step2Data>) => void }) {
return (
<div>
<h3 style={{ color: '#64ffda', margin: '0 0 12px' }}>Step 2: Professional information</h3>
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Company</label>
<input value={data.company} onChange={e => onChange({ company: e.target.value })} placeholder="Company name" style={inputStyle} />
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Position *</label>
<select value={data.role} onChange={e => onChange({ role: e.target.value })} style={inputStyle}>
<option value="">-- Select --</option>
<option value="frontend">Frontend Developer</option>
<option value="backend">Backend Developer</option>
<option value="fullstack">Fullstack Developer</option>
<option value="designer">UI/UX Designer</option>
</select>
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>Experience (years) *</label>
<input type="number" value={data.experience} onChange={e => onChange({ experience: e.target.value })} placeholder="3" min="0" max="50" style={inputStyle} />
</div>
);
}
function Step3({ data, onChange }: { data: Step3Data; onChange: (d: Partial<Step3Data>) => void }) {
const plans = [
{ value: 'free', label: 'Free', desc: 'Basic access' },
{ value: 'pro', label: 'Pro', desc: 'Full access + support' },
{ value: 'enterprise', label: 'Enterprise', desc: 'For teams + SLA' },
];
return (
<div>
<h3 style={{ color: '#64ffda', margin: '0 0 12px' }}>Step 3: Choose a plan</h3>
{plans.map(p => (
<label key={p.value} style={{
display: 'flex', alignItems: 'center', gap: 10, padding: 12, borderRadius: 6,
background: data.plan === p.value ? '#1a2744' : '#0d1117',
border: data.plan === p.value ? '1px solid #64ffda' : '1px solid #333',
cursor: 'pointer', marginBottom: 8
}}>
<input type="radio" name="plan" value={p.value} checked={data.plan === p.value}
onChange={() => onChange({ plan: p.value })} />
<div>
<strong style={{ color: data.plan === p.value ? '#64ffda' : '#e0e0e0' }}>{p.label}</strong>
<div style={{ color: '#888', fontSize: 11 }}>{p.desc}</div>
</div>
</label>
))}
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, cursor: 'pointer' }}>
<input type="checkbox" checked={data.newsletter} onChange={e => onChange({ newsletter: e.target.checked })} />
I want to receive the newsletter
</label>
</div>
);
}
export default function MultiStepFormDemo() {
const [step, setStep] = useState(1);
const [data, setData] = useState<AllData>({
firstName: '', lastName: '', email: '',
company: '', role: '', experience: '',
plan: 'free', newsletter: false,
});
const [errors, setErrors] = useState<string[]>([]);
const [complete, setComplete] = useState(false);
const update = (partial: Partial<AllData>) => { setData(prev => ({ ...prev, ...partial })); setErrors([]); };
const validateStep = () => {
const errs: string[] = [];
if (step === 1) {
if (!data.firstName) errs.push('First name is required');
if (!data.lastName) errs.push('Last name is required');
if (!data.email) errs.push('Email is required');
} else if (step === 2) {
if (!data.role) errs.push('Select a position');
if (!data.experience) errs.push('Enter your experience');
}
setErrors(errs);
return errs.length === 0;
};
const next = () => { if (validateStep()) setStep(s => Math.min(s + 1, TOTAL_STEPS)); };
const prev = () => { setErrors([]); setStep(s => Math.max(s - 1, 1)); };
const submit = (e: React.FormEvent) => { e.preventDefault(); if (validateStep()) setComplete(true); };
if (complete) {
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<div style={{ maxWidth: 400, margin: '0 auto', textAlign: 'center' }}>
<div style={{ fontSize: 40, marginBottom: 12 }}>β
</div>
<h2 style={{ color: '#64ffda' }}>Registration complete!</h2>
<div style={{ background: '#0d1117', borderRadius: 8, padding: 12, marginTop: 12, textAlign: 'left', fontSize: 12 }}>
<p><strong>Name:</strong> {data.firstName} {data.lastName}</p>
<p><strong>Email:</strong> {data.email}</p>
<p><strong>Company:</strong> {data.company || 'None'}</p>
<p><strong>Position:</strong> {data.role}</p>
<p><strong>Experience:</strong> {data.experience} years</p>
<p><strong>Plan:</strong> {data.plan}</p>
<p><strong>Newsletter:</strong> {data.newsletter ? 'Yes' : 'No'}</p>
</div>
<button onClick={() => { setComplete(false); setStep(1); setData({ firstName: '', lastName: '', email: '', company: '', role: '', experience: '', plan: 'free', newsletter: false }); }}
style={{ marginTop: 12, padding: '8px 16px', borderRadius: 6, border: '1px solid #64ffda', background: 'transparent', color: '#64ffda', cursor: 'pointer', fontFamily: 'monospace' }}>
New registration
</button>
</div>
</div>
);
}
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>Multi-Step Form</h1>
<p style={{ color: '#888', fontSize: 13, marginBottom: 16 }}>
A 3-step registration process with validation at each step.
</p>
<div style={{ maxWidth: 400 }}>
<StepIndicator current={step} total={TOTAL_STEPS} />
{errors.length > 0 && (
<div role="alert" style={{ padding: 10, background: '#3e1010', borderRadius: 6, marginBottom: 12, border: '1px solid #f44336' }}>
{errors.map((err, i) => <p key={i} style={{ color: '#f44336', fontSize: 12, margin: '2px 0' }}>{err}</p>)}
</div>
)}
<form onSubmit={submit}>
{step === 1 && <Step1 data={data} onChange={update} />}
{step === 2 && <Step2 data={data} onChange={update} />}
{step === 3 && <Step3 data={data} onChange={update} />}
<div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
{step > 1 && (
<button type="button" onClick={prev} style={{
flex: 1, padding: '10px', borderRadius: 6, border: '1px solid #444',
background: 'transparent', color: '#aaa', cursor: 'pointer', fontFamily: 'monospace'
}}>Back</button>
)}
{step < TOTAL_STEPS ? (
<button type="button" onClick={next} style={{
flex: 1, padding: '10px', borderRadius: 6, border: 'none',
background: '#64ffda', color: '#0f0f23', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'monospace'
}}>Next</button>
) : (
<button type="submit" style={{
flex: 1, padding: '10px', borderRadius: 6, border: 'none',
background: '#4caf50', color: '#fff', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'monospace'
}}>Register</button>
)}
</div>
</form>
</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. Form optimization for performance includes:
2. Optimistic updates in forms mean:
These are 2 of 6 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the useForm syntax with zodResolver integration
- Vertical ordering
Arrange the elements in the correct order: Select file β Client validation β Upload
- Horizontal ordering
Arrange the ErrorMessage component syntax for displaying errors
- Vertical ordering
Arrange the steps in the form validation pipeline in order
- Vertical ordering
Arrange the steps in a multi-step order form in order
- Click in order
Arrange the form element syntax with action
- Click in order
Arrange the Zod validation chain for a password
- Horizontal ordering
Arrange the pattern for accessing the email field error message in formState
- Vertical ordering
Arrange the elements in the correct order: Client-side validation β Form submission
- Horizontal ordering
Arrange the form syntax with Server Action in Next.js
- Horizontal ordering
Arrange the syntax for creating a FormData object from a form element
- Code editor
Create a complete security framework: 1. Authentication System - multi-provider OAuth with custom JWT implementation 2. Authorization Engine - RBAC/ABAC with fine-grained permissions 3. Session Management - secure session handling with auto-logout 4. Data Protection - end-to-end encryption with key management 5. Security Headers - CSP, HSTS, XSS protection configuration 6. Input Validation - advanced sanitization with custom validators 7. Rate Limiting - distributed rate limiting with Redis 8. Audit System - comprehensive logging with anomaly detection 9. Penetration Testing - automated security scanning 10. Compliance Tools - GDPR, CCPA compliance automation Use enterprise patterns: NextAuth.js, jose, bcryptjs, helmet, rate-limiter.
Tasks after this lesson
- QuestionForm optimization for performance includes:
- QuestionOptimistic updates in forms mean:
- Put in orderuseForm Syntax with zodResolver
- QuestionCSRF protection in forms requires:
- Put in orderSequence: Select file β Client validation β ...
- Put in orderErrorMessage Component Syntax
- Put in orderSequence: Form Validation Pipeline
- QuestionReact Final Form vs React Hook Form - the main difference is:
- Put in orderSequence: Multi-Step Form Steps
- Click in orderForm Element Syntax with action
- Click in orderZod Validation Chain for Password
- Put in orderAccessing Form Errors in React Hook Form
- Put in orderSequence: Client-side validation β Form submission
- Put in orderForm Syntax with Server Action
- QuestionReal-Time Form Validation
- Put in orderCreating FormData from a Form Element
- QuestionForm Security Layers
- Coding taskForm Validation and Security System - Step by Step
- Project to submitForms and Server Actions Project
- VideoSummary: Forms and Server Actions in Next.js