{"slug": "building-a-type-safe-api-layer-in-next-js-app-router-with-zod-and-server-actions", "title": "Building a Type-Safe API Layer in Next.js App Router With Zod and Server Actions", "summary": "A developer at pixova.io built a type-safe API layer for Next.js App Router using Zod validation and discriminated union types for Server Actions. The pattern ensures runtime validation, consistent error handling, and type safety across the client-server boundary, as demonstrated in the generation pipeline for the company's free AI wallpaper maker.", "body_md": "Server Actions in Next.js App Router look deceptively simple — write an async function, mark it with `'use server'`\n\n, call it from a Client Component. The surface area is small.\n\nThe problems surface when you start thinking about validation, error handling, and type safety across the client-server boundary. Without a deliberate approach, you end up with untyped form data on the server, error handling that varies across actions, and client code that can't trust the shape of what comes back.\n\nHere's the pattern I landed on for type-safe Server Actions with Zod validation and consistent error handling, from building the generation pipeline powering the [free AI wallpaper maker](https://pixova.io/blog/ai-wallpaper-maker-free) at pixova.io.\n\nThe simplest Server Action works fine for prototypes:\n\n``` js\n'use server';\n\nexport async function submitForm(formData: FormData) {\n  const prompt = formData.get('prompt') as string;\n  // No validation, no type safety, any error handling is ad hoc\n  const result = await generateImage(prompt);\n  return result;\n}\n```\n\nThe issues:\n\n`formData.get('prompt')`\n\nreturns `string | null | File`\n\n— the `as string`\n\ncast hides a bug waiting to happenStart with a discriminated union for action results:\n\n```\n// lib/types/action.ts\nexport type ActionSuccess<T> = {\n  success: true;\n  data: T;\n};\n\nexport type ActionError = {\n  success: false;\n  error: string;\n  fieldErrors?: Record<string, string[]>;\n};\n\nexport type ActionResult<T> = ActionSuccess<T> | ActionError;\n```\n\nEvery Server Action returns `Promise<ActionResult<T>>`\n\n. The client always knows whether the action succeeded and what shape the data has.\n\n``` js\n// lib/schemas/generate.ts\nimport { z } from 'zod';\n\nexport const GenerateSchema = z.object({\n  prompt: z\n    .string()\n    .min(3, 'Prompt must be at least 3 characters')\n    .max(500, 'Prompt must be under 500 characters')\n    .trim(),\n  aspectRatio: z.enum(['1:1', '16:9', '9:16', '4:5']).default('1:1'),\n  style: z.string().optional(),\n});\n\nexport type GenerateInput = z.infer<typeof GenerateSchema>;\njs\n// app/actions/generate.ts\n'use server';\n\nimport { z } from 'zod';\nimport { GenerateSchema, GenerateInput } from '@/lib/schemas/generate';\nimport { ActionResult } from '@/lib/types/action';\n\ntype GenerateResult = {\n  jobId: string;\n  estimatedSeconds: number;\n};\n\nexport async function generateImageAction(\n  input: GenerateInput\n): Promise<ActionResult<GenerateResult>> {\n  // Validate — even though TypeScript already knows the type,\n  // runtime validation catches anything that slips through\n  const parsed = GenerateSchema.safeParse(input);\n\n  if (!parsed.success) {\n    return {\n      success: false,\n      error: 'Invalid input',\n      fieldErrors: parsed.error.flatten().fieldErrors as Record<string, string[]>,\n    };\n  }\n\n  try {\n    const { prompt, aspectRatio, style } = parsed.data;\n\n    // Your business logic here\n    const job = await submitGenerationJob({ prompt, aspectRatio, style });\n\n    return {\n      success: true,\n      data: {\n        jobId: job.id,\n        estimatedSeconds: job.estimatedDuration,\n      },\n    };\n  } catch (error) {\n    // Log server-side for debugging\n    console.error('Generation failed:', error);\n\n    // Return user-friendly error to client\n    return {\n      success: false,\n      error: 'Generation failed. Please try again.',\n    };\n  }\n}\njs\n// hooks/useGenerate.ts\n'use client';\n\nimport { useState, useTransition } from 'react';\nimport { generateImageAction } from '@/app/actions/generate';\nimport { GenerateInput } from '@/lib/schemas/generate';\n\nexport function useGenerate() {\n  const [isPending, startTransition] = useTransition();\n  const [result, setResult] = useState<{ jobId: string } | null>(null);\n  const [error, setError] = useState<string | null>(null);\n\n  const generate = (input: GenerateInput) => {\n    setError(null);\n    setResult(null);\n\n    startTransition(async () => {\n      const response = await generateImageAction(input);\n\n      if (response.success) {\n        setResult({ jobId: response.data.jobId });\n      } else {\n        setError(response.error);\n      }\n    });\n  };\n\n  return { generate, isPending, result, error };\n}\njs\n// components/GenerateForm.tsx\n'use client';\n\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { GenerateSchema, GenerateInput } from '@/lib/schemas/generate';\nimport { useGenerate } from '@/hooks/useGenerate';\n\nexport function GenerateForm() {\n  const { generate, isPending, error } = useGenerate();\n\n  const { register, handleSubmit, formState: { errors } } = useForm<GenerateInput>({\n    resolver: zodResolver(GenerateSchema),\n    defaultValues: {\n      aspectRatio: '1:1',\n    },\n  });\n\n  return (\n    <form onSubmit={handleSubmit(generate)} className=\"flex flex-col gap-4\">\n      <div>\n        <textarea\n          {...register('prompt')}\n          placeholder=\"Describe what you want to generate...\"\n          className=\"w-full p-3 rounded-xl border border-border bg-card \n            text-foreground resize-none h-24 focus:outline-none \n            focus:ring-2 focus:ring-orange-500\"\n        />\n        {errors.prompt && (\n          <p className=\"text-sm text-red-500 mt-1\">{errors.prompt.message}</p>\n        )}\n      </div>\n\n      <select\n        {...register('aspectRatio')}\n        className=\"p-2 rounded-lg border border-border bg-card text-foreground\"\n      >\n        <option value=\"1:1\">Square (1:1)</option>\n        <option value=\"16:9\">Landscape (16:9)</option>\n        <option value=\"9:16\">Portrait (9:16)</option>\n        <option value=\"4:5\">Instagram (4:5)</option>\n      </select>\n\n      {error && (\n        <p className=\"text-sm text-red-500\">{error}</p>\n      )}\n\n      <button\n        type=\"submit\"\n        disabled={isPending}\n        className=\"px-6 py-3 bg-orange-500 text-white rounded-full \n          font-medium hover:bg-orange-600 transition-colors\n          disabled:opacity-50 disabled:cursor-not-allowed\"\n      >\n        {isPending ? 'Generating...' : 'Generate'}\n      </button>\n    </form>\n  );\n}\n```\n\nFor larger applications with many actions, a wrapper reduces boilerplate:\n\n``` js\n// lib/action-wrapper.ts\nimport { z } from 'zod';\nimport { ActionResult } from './types/action';\n\nexport function createAction<TInput, TOutput>(\n  schema: z.ZodSchema<TInput>,\n  handler: (input: TInput) => Promise<TOutput>\n) {\n  return async (input: unknown): Promise<ActionResult<TOutput>> => {\n    const parsed = schema.safeParse(input);\n\n    if (!parsed.success) {\n      return {\n        success: false,\n        error: 'Validation failed',\n        fieldErrors: parsed.error.flatten().fieldErrors as Record<string, string[]>,\n      };\n    }\n\n    try {\n      const data = await handler(parsed.data);\n      return { success: true, data };\n    } catch (error) {\n      console.error('Action error:', error);\n      return { \n        success: false, \n        error: error instanceof Error ? error.message : 'Something went wrong' \n      };\n    }\n  };\n}\n\n// Usage\nexport const generateImageAction = createAction(\n  GenerateSchema,\n  async (input) => {\n    const job = await submitGenerationJob(input);\n    return { jobId: job.id };\n  }\n);\n```\n\nWith this pattern in place:\n\n`ActionResult<T>`\n\nServer Actions are async functions — they're straightforward to unit test:\n\n``` js\n// __tests__/actions/generate.test.ts\nimport { generateImageAction } from '@/app/actions/generate';\n\n// Mock the generation service\njest.mock('@/lib/generation', () => ({\n  submitGenerationJob: jest.fn(),\n}));\n\nimport { submitGenerationJob } from '@/lib/generation';\nconst mockSubmit = submitGenerationJob as jest.Mock;\n\ndescribe('generateImageAction', () => {\n  it('returns success with valid input', async () => {\n    mockSubmit.mockResolvedValue({ id: 'job-123', estimatedDuration: 8 });\n\n    const result = await generateImageAction({\n      prompt: 'A sunset over mountains',\n      aspectRatio: '16:9',\n    });\n\n    expect(result.success).toBe(true);\n    if (result.success) {\n      expect(result.data.jobId).toBe('job-123');\n    }\n  });\n\n  it('returns validation error for short prompt', async () => {\n    const result = await generateImageAction({\n      prompt: 'hi', // Too short\n      aspectRatio: '1:1',\n    });\n\n    expect(result.success).toBe(false);\n    if (!result.success) {\n      expect(result.fieldErrors?.prompt).toBeDefined();\n    }\n  });\n\n  it('returns error when service throws', async () => {\n    mockSubmit.mockRejectedValue(new Error('Service unavailable'));\n\n    const result = await generateImageAction({\n      prompt: 'A valid prompt that is long enough',\n      aspectRatio: '1:1',\n    });\n\n    expect(result.success).toBe(false);\n  });\n});\n```\n\nTesting with the `ActionResult`\n\ntype makes assertions clean — the discriminated union means TypeScript narrows the type inside the `if (result.success)`\n\nblock, so you get full type checking on both success and error paths.\n\n**Forgetting that Server Actions run on the server.** They don't have access to `window`\n\n, `document`\n\n, or browser APIs. If you're calling a Server Action from a component that also uses browser APIs, make sure the action itself doesn't try to use them.\n\n**Not handling revalidatePath or revalidateTag after mutations.** If an action mutates data and the page should reflect that, you need to explicitly invalidate the cache:\n\n``` js\nimport { revalidatePath } from 'next/cache';\n\nexport async function deleteItem(id: string): Promise<ActionResult<void>> {\n  try {\n    await db.items.delete(id);\n    revalidatePath('/items'); // Update the cache\n    return { success: true, data: undefined };\n  } catch {\n    return { success: false, error: 'Failed to delete item' };\n  }\n}\n```\n\n**Passing complex objects when primitives work.** Server Actions serialize arguments across the network. Simple types (strings, numbers, plain objects) serialize cleanly. Class instances, functions, and non-serializable objects don't. Keep action inputs to JSON-serializable types.", "url": "https://wpnews.pro/news/building-a-type-safe-api-layer-in-next-js-app-router-with-zod-and-server-actions", "canonical_source": "https://dev.to/aon_infotech_3a1b6ff525fc/building-a-type-safe-api-layer-in-nextjs-app-router-with-zod-and-server-actions-ma2", "published_at": "2026-06-28 07:10:56+00:00", "updated_at": "2026-06-28 07:33:29.928754+00:00", "lang": "en", "topics": ["developer-tools", "artificial-intelligence", "generative-ai"], "entities": ["pixova.io", "Next.js", "Zod", "Server Actions", "App Router"], "alternates": {"html": "https://wpnews.pro/news/building-a-type-safe-api-layer-in-next-js-app-router-with-zod-and-server-actions", "markdown": "https://wpnews.pro/news/building-a-type-safe-api-layer-in-next-js-app-router-with-zod-and-server-actions.md", "text": "https://wpnews.pro/news/building-a-type-safe-api-layer-in-next-js-app-router-with-zod-and-server-actions.txt", "jsonld": "https://wpnews.pro/news/building-a-type-safe-api-layer-in-next-js-app-router-with-zod-and-server-actions.jsonld"}}