typescriptintermediate

Server Action with Form Validation

Next.js Server Action handling form submissions with validation, error messages, and redirect on success.

typescript
'use server';

import { redirect } from 'next/navigation';

interface FormState {
  errors: Record<string, string>;
  message?: string;
}

export async function createPost(
  _prevState: FormState,
  formData: FormData
): Promise<FormState> {
  const title = formData.get('title') as string;
  const content = formData.get('content') as string;

  const errors: Record<string, string> = {};

  if (!title || title.length < 3) {
    errors.title = 'Title must be at least 3 characters';
  }
  if (!content || content.length < 10) {
    errors.content = 'Content must be at least 10 characters';
  }

  if (Object.keys(errors).length > 0) {
    return { errors };
  }

  // Replace with your database call
  const post = { id: crypto.randomUUID(), title, content };
  console.log('Created:', post);

  redirect(`/posts/${post.id}`);
}

// Client component usage:
// 'use client';
// import { useActionState } from 'react';
// import { createPost } from './actions';
//
// const [state, action, pending] = useActionState(createPost, { errors: {} });
// <form action={action}>
//   <input name="title" />
//   {state.errors.title && <p>{state.errors.title}</p>}
//   <textarea name="content" />
//   <button disabled={pending}>Submit</button>
// </form>

Use Cases

  • Blog post creation
  • Contact forms
  • User profile updates

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.