DAILY NEWS

Stay Ahead, Stay Informed – Every Day

Advertisement
Building a Type-Safe API Layer in Next.js App Router With Zod and Server Actions



Server Actions in Next.js App Router look deceptively simple — write an async function, mark it with ‘use server’, call it from a Client Component. The surface area is small.

The 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.

Here’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 at pixova.io.

The Problem With Naive Server Actions

The simplest Server Action works fine for prototypes:

‘use server’;

export async function submitForm(formData: FormData) {
const prompt = formData.get(‘prompt’) as string;
// No validation, no type safety, any error handling is ad hoc
const result = await generateImage(prompt);
return result;
}

Enter fullscreen mode

Exit fullscreen mode

The issues:

formData.get(‘prompt’) returns string | null | File — the as string cast hides a bug waiting to happen
No validation means invalid input reaches your business logic
Error handling is whatever you add ad hoc to each action

– The return type isn’t defined, so the client has no type information

The Foundation — A Result Type

Start with a discriminated union for action results:

// lib/types/action.ts
export type ActionSuccessT> = {
success: true;
data: T;
};

export type ActionError = {
success: false;
error: string;
fieldErrors?: Recordstring, string()>;
};

export type ActionResultT> = ActionSuccessT> | ActionError;

Enter fullscreen mode

Exit fullscreen mode

Every Server Action returns Promise>. The client always knows whether the action succeeded and what shape the data has.

Adding Zod Validation

// lib/schemas/generate.ts
import { z } from ‘zod’;

export const GenerateSchema = z.object({
prompt: z
.string()
.min(3, ‘Prompt must be at least 3 characters’)
.max(500, ‘Prompt must be under 500 characters’)
.trim(),
aspectRatio: z.enum((‘1:1′, ’16:9’, ‘9:16’, ‘4:5’)).default(‘1:1’),
style: z.string().optional(),
});

export type GenerateInput = z.infertypeof GenerateSchema>;

Enter fullscreen mode

Exit fullscreen mode

The Server Action With Full Type Safety

// app/actions/generate.ts
‘use server’;

import { z } from ‘zod’;
import { GenerateSchema, GenerateInput } from ‘@/lib/schemas/generate’;
import { ActionResult } from ‘@/lib/types/action’;

type GenerateResult = {
jobId: string;
estimatedSeconds: number;
};

export async function generateImageAction(
input: GenerateInput
): PromiseActionResultGenerateResult>> {
// Validate — even though TypeScript already knows the type,
// runtime validation catches anything that slips through
const parsed = GenerateSchema.safeParse(input);

if (!parsed.success) {
return {
success: false,
error: ‘Invalid input’,
fieldErrors: parsed.error.flatten().fieldErrors as Recordstring, string()>,
};
}

try {
const { prompt, aspectRatio, style } = parsed.data;

// Your business logic here
const job = await submitGenerationJob({ prompt, aspectRatio, style });

return {
success: true,
data: {
jobId: job.id,
estimatedSeconds: job.estimatedDuration,
},
};
} catch (error) {
// Log server-side for debugging
console.error(‘Generation failed:’, error);

// Return user-friendly error to client
return {
success: false,
error: ‘Generation failed. Please try again.’,
};
}
}

Enter fullscreen mode

Exit fullscreen mode

The Client-Side Hook

// hooks/useGenerate.ts
‘use client’;

import { useState, useTransition } from ‘react’;
import { generateImageAction } from ‘@/app/actions/generate’;
import { GenerateInput } from ‘@/lib/schemas/generate’;

export function useGenerate() {
const (isPending, startTransition) = useTransition();
const (result, setResult) = useState{ jobId: string } | null>(null);
const (error, setError) = useStatestring | null>(null);

const generate = (input: GenerateInput) => {
setError(null);
setResult(null);

startTransition(async () => {
const response = await generateImageAction(input);

if (response.success) {
setResult({ jobId: response.data.jobId });
} else {
setError(response.error);
}
});
};

return { generate, isPending, result, error };
}

Enter fullscreen mode

Exit fullscreen mode

The Form Component

// components/GenerateForm.tsx
‘use client’;

import { useForm } from ‘react-hook-form’;
import { zodResolver } from ‘@hookform/resolvers/zod’;
import { GenerateSchema, GenerateInput } from ‘@/lib/schemas/generate’;
import { useGenerate } from ‘@/hooks/useGenerate’;

export function GenerateForm() {
const { generate, isPending, error } = useGenerate();

const { register, handleSubmit, formState: { errors } } = useFormGenerateInput>({
resolver: zodResolver(GenerateSchema),
defaultValues: {
aspectRatio: ‘1:1’,
},
});

return (
form onSubmit={handleSubmit(generate)} className=”flex flex-col gap-4″>
div>
textarea
{…register(‘prompt’)}
placeholder=”Describe what you want to generate…”
className=”w-full p-3 rounded-xl border border-border bg-card
text-foreground resize-none h-24 focus:outline-none
focus:ring-2 focus:ring-orange-500″
/>
{errors.prompt && (
p className=”text-sm text-red-500 mt-1″>{errors.prompt.message}p>
)}
div>

select
{…register(‘aspectRatio’)}
className=”p-2 rounded-lg border border-border bg-card text-foreground”
>
option value=”1:1″>Square (1:1)option>
option value=”16:9″>Landscape (16:9)option>
option value=”9:16″>Portrait (9:16)option>
option value=”4:5″>Instagram (4:5)option>
select>

{error && (
p className=”text-sm text-red-500″>{error}p>
)}

button
type=”submit”
disabled={isPending}
className=”px-6 py-3 bg-orange-500 text-white rounded-full
font-medium hover:bg-orange-600 transition-colors
disabled:opacity-50 disabled:cursor-not-allowed”
>
{isPending ? ‘Generating…’ : ‘Generate’}
button>
form>
);
}

Enter fullscreen mode

Exit fullscreen mode

A Reusable Action Wrapper

For larger applications with many actions, a wrapper reduces boilerplate:

// lib/action-wrapper.ts
import { z } from ‘zod’;
import { ActionResult } from ‘./types/action’;

export function createActionTInput, TOutput>(
schema: z.ZodSchemaTInput>,
handler: (input: TInput) => PromiseTOutput>
) {
return async (input: unknown): PromiseActionResultTOutput>> => {
const parsed = schema.safeParse(input);

if (!parsed.success) {
return {
success: false,
error: ‘Validation failed’,
fieldErrors: parsed.error.flatten().fieldErrors as Recordstring, string()>,
};
}

try {
const data = await handler(parsed.data);
return { success: true, data };
} catch (error) {
console.error(‘Action error:’, error);
return {
success: false,
error: error instanceof Error ? error.message : ‘Something went wrong’
};
}
};
}

// Usage
export const generateImageAction = createAction(
GenerateSchema,
async (input) => {
const job = await submitGenerationJob(input);
return { jobId: job.id };
}
);

Enter fullscreen mode

Exit fullscreen mode

The Payoff

With this pattern in place:

Every action has a consistent interface — ActionResult

Validation errors surface to the client with field-level detail
TypeScript knows the exact shape of success and error responses
Error handling is centralized rather than ad hoc per action
Adding a new action means writing the schema and handler — the boilerplate is handled
The upfront investment in the wrapper and types pays off quickly across a codebase with more than a handful of Server Actions.

Testing Server Actions

Server Actions are async functions — they’re straightforward to unit test:

// __tests__/actions/generate.test.ts
import { generateImageAction } from ‘@/app/actions/generate’;

// Mock the generation service
jest.mock(‘@/lib/generation’, () => ({
submitGenerationJob: jest.fn(),
}));

import { submitGenerationJob } from ‘@/lib/generation’;
const mockSubmit = submitGenerationJob as jest.Mock;

describe(‘generateImageAction’, () => {
it(‘returns success with valid input’, async () => {
mockSubmit.mockResolvedValue({ id: ‘job-123’, estimatedDuration: 8 });

const result = await generateImageAction({
prompt: ‘A sunset over mountains’,
aspectRatio: ’16:9′,
});

expect(result.success).toBe(true);
if (result.success) {
expect(result.data.jobId).toBe(‘job-123’);
}
});

it(‘returns validation error for short prompt’, async () => {
const result = await generateImageAction({
prompt: ‘hi’, // Too short
aspectRatio: ‘1:1’,
});

expect(result.success).toBe(false);
if (!result.success) {
expect(result.fieldErrors?.prompt).toBeDefined();
}
});

it(‘returns error when service throws’, async () => {
mockSubmit.mockRejectedValue(new Error(‘Service unavailable’));

const result = await generateImageAction({
prompt: ‘A valid prompt that is long enough’,
aspectRatio: ‘1:1’,
});

expect(result.success).toBe(false);
});
});

Enter fullscreen mode

Exit fullscreen mode

Testing with the ActionResult type makes assertions clean — the discriminated union means TypeScript narrows the type inside the if (result.success) block, so you get full type checking on both success and error paths.

Common Pitfalls

Forgetting that Server Actions run on the server. They don’t have access to window, document, 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.

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:

import { revalidatePath } from ‘next/cache’;

export async function deleteItem(id: string): PromiseActionResultvoid>> {
try {
await db.items.delete(id);
revalidatePath(‘/items’); // Update the cache
return { success: true, data: undefined };
} catch {
return { success: false, error: ‘Failed to delete item’ };
}
}

Enter fullscreen mode

Exit fullscreen mode

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.



Source link

DESIGN.md Anatomy: How Tokens and Prose Work Together



A DESIGN.md has two parts: YAML front matter with machine-readable design tokens, and a markdown body with human-readable rationale. Tokens give an agent exact values; prose gives it the rules. Pairing them is the format’s core insight.

The front matter: tokens

The front matter holds your colors, typography, spacing, rounded corners and components as typed values. It opens and closes with three dashes:


colors:
primary: “#1A1C1E”
surface: “#FFFFFF”
spacing:
sm: 8px
md: 16px

Enter fullscreen mode

Exit fullscreen mode

This gives the agent precise values to use directly.

The body: prose

Below the front matter is the rationale, in canonical sections:

## Overview
A calm, focused reading environment. The UI recedes so content leads.

## Colors
Warm neutrals carry the interface. The accent is reserved strictly
for interactive elements – never decorative.

Enter fullscreen mode

Exit fullscreen mode

Why pair them?

A hex value tells the agent what a color is. Only prose can tell it that this color is the sole interaction driver and must never be used decoratively.

# A tokens-only file: just data, no rules.
# A prose-only file: intent, but no precise values.
# DESIGN.md: both, so the agent applies the system correctly.

Enter fullscreen mode

Exit fullscreen mode

The canonical sections

Overview – the personality

Colors – roles and rules

Typography – the job of each style

Layout – grid and spacing

Elevation & Depth – how hierarchy is built

Do’s and Don’ts – hard guardrails

FAQ

Is the front matter required? In principle optional, but in practice it is the heart of the file.Can I use only prose? You can, but you lose precise values. The format is designed for both.

Bottom line

Tokens are the values; prose is the meaning. A DESIGN.md works because it carries both in one file the agent reads together.

Free starter: The format, a complete annotated example, and the core idea are on a free cheat sheet: DESIGN.md Quick-Start Cheat Sheet

Go deeper: The full guide covers the entire format — the token schema, the CLI in depth, accessibility, Tailwind and DTCG export, agent integration, and a complete walkthrough: DESIGN.md: The Complete Guide to Design Systems for AI Agents

Do you write rationale in your design docs, or just list the tokens? Curious how teams handle the ‘why’ in the comments.



Source link

Connection architectures for WordPress maintenance tools — mapping four products on a two-axis grid



While writing the comparison pages for ManageWP, MainWP, WP Umbrella, and InfiniteWP on our LP, I tried to line up the four products under a single “connection method” column — and got stuck. The same ManageWP gets called a “Hosted SaaS tool” in one source, a “Worker plugin tool” in another, and a “self-hosted” tool in yet another.

On closer look, these labels are mixing two distinct axes into one column. Once you separate them, the four products fit cleanly into a two-axis, six-cell grid. This post lays out that grid and walks through what each cell means for day-to-day operations.

Axis 1 — What gets installed on the client site

The first axis asks what the maintenance tool installs on the WordPress sites it manages. There are two answers.

A. Worker / Child plugin: Each managed site gets a dedicated plugin from the maintenance tool. ManageWP Worker, MainWP Child, WP Umbrella, InfiniteWP Client — the names differ, but they all play the same role: a “gateway plugin” that exposes a REST/HTTP endpoint the dashboard talks to.

B. Direct SSH + WP-CLI: Nothing gets installed on the site. The tool logs in via SSH and invokes WP-CLI directly on the server.

The difference shows up as how invasive the tool is on the client side. The plugin route carries the cost of “a vulnerability in the gateway plugin cascades to every managed site” and “you owe the client an explanation for the extra plugin.” The SSH route carries the constraint of “hosts that disallow SSH are out of reach” and “operators need basic SSH literacy.”

Axis 2 — Where the dashboard lives

The second axis asks where the dashboard itself runs. There are three answers.

① Hosted SaaS: The dashboard runs on infrastructure operated by the vendor. Site credentials live in their cloud — a trust model where the vendor holds your secrets.

② Self-hosted: You stand up your own WordPress site or server and install the dashboard there. The data stays in your control, but you also inherit the operational burden of maintaining that dashboard platform itself.

③ Desktop app: The dashboard runs on your local PC. Data stays local — no cloud component, no server to operate.

Axis 2 determines where the data lives and where the responsibility line is drawn. Who holds the credentials? Who is on the hook when something goes wrong? That cell choice shapes the risk structure your team takes on.

The two axes overlaid — a six-cell grid

Dashboard ↓ / Connection →
Worker / Child plugin
Direct SSH + WP-CLI

① Hosted SaaS
ManageWP, WP Umbrella
(industry gap)

② Self-hosted
MainWP, InfiniteWP
(industry gap)

③ Desktop app
(industry gap)
WP Maintenance Manager

The four major products cluster in the top two cells of the “plugin” column. The “SSH” column is almost entirely blank. Let’s walk through the three occupied cells first.

Cell 1 — Hosted SaaS × plugin (ManageWP, WP Umbrella)

The industry’s most classic configuration: browser access from anywhere, the vendor handles infrastructure updates and redundancy, and uptime monitoring fits naturally. WP Umbrella’s EU-based hosting, which leans on data-residency as a selling point, is a story this cell makes possible.

The trade-off is that client credentials get handed to a third-party cloud. A breach at the vendor cascades to every managed site, and your operations are tied to the vendor’s business continuity. Pricing tends to layer “per-site × add-on” charges on top of the monthly base.

Cell 2 — Self-hosted × plugin (MainWP, InfiniteWP)

For teams that don’t want credentials in a third-party cloud but still want the compatibility of plugin-based connections. Full data ownership and affinity with one-time-purchase and annual-license models are the upsides.

The trade-off is that the burden of maintaining the dashboard platform falls on you. MainWP requires you to keep updating and securing the very WordPress site that runs the dashboard; InfiniteWP’s panel server needs the same kind of care. A meta-recursion of “you maintain the tool that maintains your tools” is built into this cell. If the dashboard platform is compromised, the credentials for every connected site can leak from one place.

Cell 3 — Desktop × SSH (WP Maintenance Manager)

The dashboard runs as a desktop app on your PC, and the tool connects to sites directly over SSH. Three properties stand out: data lives only on the local PC, no infrastructure to operate, and nothing installed on client sites. The cascading-vulnerability risk of a gateway plugin structurally doesn’t exist.

The trade-off is that continuous uptime monitoring isn’t a natural fit — when the PC is asleep, the monitoring loop isn’t running. Hosts that disallow SSH also fall outside the supported set, so the hosting coverage is narrower than the other cells.

Why the three empty cells stay empty

The remaining cells have essentially no products. There are structural reasons.

Hosted SaaS × SSH struggles because handing SSH private keys to a cloud vendor is a trust model the market resists. Plugin-based connections keep credentials on the site side; storing and using SSH keys inside a third-party cloud raises the audit bar significantly.

Self-hosted × SSH is technically possible, but layers two costs at once: running your own dashboard platform and absorbing the SSH connectivity constraints. Teams that opt into self-hosting rarely want to give up plugin-route compatibility on top of that.

Desktop × plugin fights a fundamental mismatch: some gateway plugins assume continuous push communication to the dashboard, which doesn’t reconcile with a desktop app that only runs when the user’s PC is on.

Closing — how to choose a cell

Cell selection is a trade-off between acceptable costs and where the responsibility line sits. Three questions tend to do most of the work during evaluation.

Credentials in a third-party cloud, or kept locally? (Axis 2)

A maintenance plugin on every client site, or none? (Axis 1)

Operating an infrastructure tier yourself, or not? (Axis 2, only the self-hosted row adds this)

The industry has consolidated into “Hosted SaaS × plugin” and “Self-hosted × plugin” largely for historical reasons — SSH-route constraints (host coverage and the SSH knowledge requirement on operators) made industry-wide adoption hard. Choosing the SSH column structurally avoids the client-side invasiveness and gateway-plugin cascade risk that the plugin column carries.

There’s no single “correct” architecture. Operating style, client contracts, and data-handling requirements all shift the right cell. Carrying this six-cell map in your head makes it easier to ask the right comparison questions when picking a maintenance tool — and to see which trade-offs actually matter for your own operations.



Source link