Skip to content

NarixHine/uni-chem / .agents/skills/safe-action-middleware

safe-action-middleware

Verified

Use when implementing middleware for next-safe-action -- authentication, authorization, logging, rate limiting, error interception, context extension, or creating standalone reusable middleware with createMiddleware() or createValidatedMiddleware(). Covers both use() (pre-validation) and useValidated() (post-validation) middleware.

FileKindSize
SKILL.mdskill md7.0 KB
auth-patterns.mdmarkdown3.2 KB
logging-monitoring.mdmarkdown4.0 KB
standalone-middleware.mdmarkdown5.4 KB

standalone-middleware.md

View on GitHub
# Standalone Reusable Middleware

> **Note:** Action files require a `"use server"` directive — omitted from examples below for brevity.

## createMiddleware()

`createMiddleware()` creates type-safe, reusable middleware that can be shared across multiple clients. It uses a curried `.define()` pattern for generic type inference.

```ts
import { createMiddleware } from "next-safe-action";
```

## Basic Usage

```ts
const logMiddleware = createMiddleware().define(async ({ next, clientInput }) => {
  console.log("Input:", clientInput);
  const result = await next();
  console.log("Result:", result);
  return result;
});

// Use in any client
const client1 = createSafeActionClient().use(logMiddleware);
const client2 = createSafeActionClient().use(logMiddleware);
```

## With Type Constraints

Specify minimum requirements for the middleware using the generic parameter. The middleware will only be compatible with clients that satisfy these constraints.

```ts
// This middleware requires:
// - ctx must have userId (string)
// - metadata must have actionName (string)
const auditMiddleware = createMiddleware<{
  ctx: { userId: string };
  metadata: { actionName: string };
}>().define(async ({ next, ctx, metadata }) => {
  // ctx.userId and metadata.actionName are typed
  await db.auditLog.create({
    userId: ctx.userId,
    action: metadata.actionName,
    timestamp: new Date(),
  });

  return next();
});

// Works — authClient already provides userId in ctx
const authClient = createSafeActionClient({
  defineMetadataSchema: () => z.object({ actionName: z.string() }),
})
  .use(async ({ next }) => {
    const session = await getSession();
    return next({ ctx: { userId: session!.user.id } });
  })
  .use(auditMiddleware); // Type-safe!

// Error — baseClient doesn't have userId in ctx
const baseClient = createSafeActionClient();
baseClient.use(auditMiddleware); // TypeScript error!
```

## Constraining Server Error Type

```ts
// Middleware that expects structured server errors
const errorTrackingMiddleware = createMiddleware<{
  serverError: { message: string; code: string };
}>().define(async ({ next }) => {
  const result = await next();
  if (result.serverError) {
    // result.serverError is typed as { message: string; code: string }
    trackError(result.serverError.code);
  }
  return result;
});
```

## Context Extension

Standalone middleware can extend context just like inline middleware:

```ts
const timingMiddleware = createMiddleware().define(async ({ next }) => {
  const start = performance.now();
  const result = await next({
    ctx: { requestStartTime: start },
  });
  return result;
});

// Later middleware/action can access ctx.requestStartTime
const client = createSafeActionClient()
  .use(timingMiddleware)
  .use(async ({ next, ctx }) => {
    // ctx.requestStartTime is available and typed
    return next();
  });
```

## Composing Multiple Standalone Middleware

```ts
const withTiming = createMiddleware().define(async ({ next }) => {
  const start = performance.now();
  const result = await next({ ctx: { timing: { start } } });
  return result;
});

const withRequestId = createMiddleware().define(async ({ next }) => {
  return next({ ctx: { requestId: crypto.randomUUID() } });
});

const withAuth = createMiddleware().define(async ({ next }) => {
  const session = await getSession();
  if (!session) throw new Error("Unauthorized");
  return next({ ctx: { userId: session.user.id } });
});

// Compose in order
export const actionClient = createSafeActionClient()
  .use(withTiming)
  .use(withRequestId)
  .use(withAuth);

// Action ctx: { timing: { start: number }, requestId: string, userId: string }
```

## createValidatedMiddleware()

`createValidatedMiddleware()` creates type-safe, reusable middleware that runs **after** input validation. It follows the same curried `.define()` pattern as `createMiddleware()`.

```ts
import { createValidatedMiddleware } from "next-safe-action";
```

### Basic Usage

```ts
const logValidatedInput = createValidatedMiddleware().define(
  async ({ parsedInput, next }) => {
    console.log("Validated input:", parsedInput);
    return next();
  }
);

// Use with .useValidated()
const action = createSafeActionClient()
  .inputSchema(z.object({ name: z.string() }))
  .useValidated(logValidatedInput)
  .action(async ({ parsedInput }) => {
    // ...
  });
```

### With Type Constraints

Specify required context and input shape. The middleware will only be compatible with chains that provide matching types.

```ts
const checkOwnership = createValidatedMiddleware<{
  ctx: { user: { id: string } };
  parsedInput: { resourceId: string };
}>().define(async ({ parsedInput, ctx, next }) => {
  const resource = await db.resource.findUnique({
    where: { id: parsedInput.resourceId },
  });

  if (resource?.ownerId !== ctx.user.id) {
    throw new Error("Not authorized");
  }

  return next({ ctx: { resource } });
});

// Usage — parsedInput must include resourceId, ctx must include user.id
const action = authClient
  .inputSchema(z.object({ resourceId: z.string().uuid(), title: z.string() }))
  .useValidated(checkOwnership)
  .action(async ({ ctx }) => {
    // ctx.resource is typed and available
  });
```

### Key Difference from createMiddleware()

- `createMiddleware()` produces middleware for `.use()` — receives `clientInput` (raw, unvalidated)
- `createValidatedMiddleware()` produces middleware for `.useValidated()` — receives `parsedInput` (typed, validated) plus `clientInput`, `bindArgsParsedInputs`, `bindArgsClientInputs`
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall