/** * CSRF Protected Form Component * * A wrapper component that automatically adds CSRF protection to forms. * This component demonstrates how to integrate CSRF tokens into form submissions. */ "use client"; import type { FormEvent, ReactNode } from "react"; import { useId } from "react"; import { useCSRFForm } from "../../lib/hooks/useCSRF"; interface CSRFProtectedFormProps { children: ReactNode; action: string; method?: "POST" | "PUT" | "DELETE" | "PATCH"; onSubmit?: (formData: FormData) => Promise | void; className?: string; encType?: string; } /** * Form component with automatic CSRF protection */ export function CSRFProtectedForm({ children, action, method = "POST", onSubmit, className, encType, }: CSRFProtectedFormProps) { const { token, submitForm, addTokenToFormData } = useCSRFForm(); const handleSubmit = async (event: FormEvent) => { event.preventDefault(); const form = event.currentTarget; const formData = new FormData(form); // Add CSRF token to form data addTokenToFormData(formData); try { if (onSubmit) { // Use custom submit handler await onSubmit(formData); } else { // Use default form submission with CSRF protection const response = await submitForm(action, formData); if (!response.ok) { throw new Error(`Form submission failed: ${response.status}`); } // Handle successful submission console.log("Form submitted successfully"); } } catch (error) { console.error("Form submission error:", error); // You might want to show an error message to the user here } }; return (
{/* Hidden CSRF token field for non-JS fallback */} {token && } {children}
); } /** * Example usage component showing how to use CSRF protected forms */ export function ExampleCSRFForm() { // Generate unique IDs for form elements const nameId = useId(); const emailId = useId(); const messageId = useId(); const handleCustomSubmit = async (formData: FormData) => { // Custom form submission logic const data = Object.fromEntries(formData.entries()); console.log("Form data:", data); // You can process the form data here before submission // The CSRF token is automatically included in formData }; return (

CSRF Protected Form Example