Security Middleware

Built-in rateLimitMiddleware, originMiddleware, and csrfMiddleware

Rate Limiting

This action allows 5 requests per 10 seconds for each client. Click quickly to go over the limit. The server then says how long to wait, in retryAfter and in the Retry-After header.

Sent: 0
// server/actions/rate-limited-action.post.ts
export default defineAction({
  input: z.object({ message: z.string() }),
  middleware: [
    rateLimitMiddleware({
      limit: 5,
      window: 10000,
      headers: true,
      message: 'Too many requests, wait 10 seconds',
    }),
  ],
  handler: async ({ input }) => {
    return { echo: input.message, timestamp: Date.now() }
  },
})

// client: wait as long as the server asks, then retry once
const waitingAction = useAction(rateLimitedAction, {
  retry: { count: 1, respectRetryAfter: true, maxDelay: 10_000 },
})

Origin Check

originMiddleware rejects mutations that come from another site, from the Sec-Fetch-Site and Origin headers the browser sends, with no token to pass around. This page is on the same origin, so its request passes.

The same request from another site is rejected:

curl -X POST https://nuxt-actions-demo.vercel.app/api/_actions/origin-protected \
  -H 'content-type: application/json' \
  -H 'sec-fetch-site: cross-site' \
  -H 'origin: https://evil.example' \
  -d '{"note":"forged"}'

{
  "success": false,
  "error": {
    "code": "CSRF_ERROR",
    "message": "Cross-origin request rejected",
    "statusCode": 403
  }
}
// server/actions/origin-protected.post.ts
export default defineAction({
  input: z.object({ note: z.string() }),
  middleware: [originMiddleware()],
  handler: async ({ input }) => ({ saved: input.note, at: Date.now() }),
})

CSRF Protection

The csrfMiddleware generates a token cookie on safe requests and validates it on mutations. The client reads the cookie and sends the token in the x-csrf-token header.

Flow:1. Server sets _csrf cookie with a random token2. Client reads cookie value3. Client sends token in x-csrf-token header4. Server compares cookie vs header (timing-safe)

Token from document.cookie: none yet

// Usage in an action
export default defineAction({
  input: z.object({ title: z.string() }),
  middleware: [
    csrfMiddleware({
      cookieName: '_csrf',        // default
      headerName: 'x-csrf-token', // default
      tokenLength: 32,            // default
    }),
  ],
  handler: async ({ input }) => {
    return db.createPost(input)
  },
})

Composing Middleware

Middleware can be chained — apply rate limiting AND CSRF protection together.

export default defineAction({
  input: z.object({ amount: z.number() }),
  middleware: [
    rateLimitMiddleware({ limit: 10, window: 60000 }),
    csrfMiddleware(),
  ],
  handler: async ({ input }) => {
    return payments.charge(input.amount)
  },
})