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

auth-patterns.md

View on GitHub
# Authentication & Authorization Middleware

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

> **Tip:** Use `.use()` for auth checks that don't need input (session lookup, API key). Use `.useValidated()` for authorization checks that depend on validated input (resource ownership, org membership).

## Session Lookup

```ts
import { createSafeActionClient } from "next-safe-action";
import { getSession } from "@/lib/auth";

const actionClient = createSafeActionClient();

// Require authenticated session
export const authActionClient = actionClient.use(async ({ next }) => {
  const session = await getSession();

  if (!session?.user) {
    throw new Error("You must be logged in to perform this action.");
  }

  return next({
    ctx: {
      userId: session.user.id,
      userEmail: session.user.email,
      userRole: session.user.role,
    },
  });
});
```

## Role-Based Authorization

Layer role checks on top of the auth middleware:

```ts
// Admin-only actions
export const adminActionClient = authActionClient.use(async ({ next, ctx }) => {
  if (ctx.userRole !== "admin") {
    throw new Error("Admin access required.");
  }
  return next({ ctx });
});

// Organization member actions
// useValidated() runs after input validation — parsedInput is typed, no manual re-parsing needed
export const orgActionClient = authActionClient
  .inputSchema(z.object({ orgId: z.string().uuid() }))
  .useValidated(async ({ next, ctx, parsedInput }) => {
    // parsedInput is typed: { orgId: string }
    const membership = await db.orgMember.find({
      userId: ctx.userId,
      orgId: parsedInput.orgId,
    });

    if (!membership) {
      throw new Error("You are not a member of this organization.");
    }

    return next({
      ctx: { orgRole: membership.role, orgId: parsedInput.orgId },
    });
  });
```

## Resource Ownership

Check that the user owns the resource they're modifying:

```ts
export const updatePost = authActionClient
  .inputSchema(z.object({ postId: z.string().uuid(), title: z.string() }))
  .useValidated(async ({ next, ctx, parsedInput }) => {
    // parsedInput is typed: { postId: string; title: string }
    const post = await db.post.findById(parsedInput.postId);

    if (!post) {
      throw new Error("Post not found");
    }
    if (post.authorId !== ctx.userId) {
      throw new Error("You can only edit your own posts");
    }

    return next({ ctx: { post } }); // Pass the fetched post to avoid re-querying
  })
  .action(async ({ parsedInput, ctx }) => {
    // ctx.post is available — no need to query again
    await db.post.update(ctx.post.id, { title: parsedInput.title });
    return { success: true };
  });
```

## API Key Authentication

For actions called from external services:

```ts
export const apiActionClient = actionClient.use(async ({ next }) => {
  const headersList = await headers();
  const apiKey = headersList.get("x-api-key");

  if (!apiKey) {
    throw new Error("API key required");
  }

  const keyRecord = await db.apiKey.findByKey(apiKey);
  if (!keyRecord || keyRecord.revoked) {
    throw new Error("Invalid API key");
  }

  return next({
    ctx: { apiKeyId: keyRecord.id, permissions: keyRecord.permissions },
  });
});
```
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