@csrf-armor/nextjs

中文文档
1.4.8发布于 2026/10/06MITTypeScriptES Module构建来源已验证近 30 天下载 2.1万

CSRF protection middleware for Next.js applications

原始使用文档
文档目录13 节
  1. Quick start
  2. 1. Install
  3. 2. Set a secret
  4. 3. Add the middleware
  5. 4. Add the provider
  6. 5. Send the token
  7. Server Actions
  8. Client API
  9. <CsrfProvider config?>
  10. useCsrf()
  11. Different strategies per route
  12. Configuration
  13. License

@csrf-armor/nextjs

CSRF Armor

CI npm version License: MIT Next.js

CSRF protection for Next.js 13+ with middleware, a React provider and a useCsrf hook. Works with the App Router, the Pages Router and Server Actions. The middleware uses only Web APIs, so it runs in the Edge Runtime.

Quick start

1. Install

npm install @csrf-armor/nextjs

2. Set a secret

# .env.local — generate with: openssl rand -base64 32
CSRF_SECRET=your-generated-secret

3. Add the middleware

Create middleware.ts in your project root (or in src/). On Next.js 16 you can name it proxy.ts and export proxy instead; the code is the same.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createCsrfMiddleware } from '@csrf-armor/nextjs';

if (process.env.NODE_ENV === 'production' && !process.env.CSRF_SECRET) {
  throw new Error('CSRF_SECRET is required in production');
}

const csrfProtect = createCsrfMiddleware({
  secret: process.env.CSRF_SECRET,
  cookie: { secure: process.env.NODE_ENV === 'production' },
});

export async function middleware(request: NextRequest) {
  const result = await csrfProtect(request, NextResponse.next());

  // The helper only reports the outcome; you must block failures yourself.
  // On failure result.response is still the NextResponse.next() you passed in.
  if (!result.success) {
    console.warn('CSRF validation failed', {
      method: request.method,
      url: request.url,
      reason: result.reason,
    });
    return NextResponse.json({ error: 'CSRF validation failed' }, { status: 403 });
  }

  return result.response;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};

4. Add the provider

// App Router: app/layout.tsx
import { CsrfProvider } from '@csrf-armor/nextjs/client';

export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
  return (
    <html lang="en">
      <body>
        <CsrfProvider>{children}</CsrfProvider>
      </body>
    </html>
  );
}
// Pages Router: pages/_app.tsx
import type { AppProps } from 'next/app';
import { CsrfProvider } from '@csrf-armor/nextjs/client';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <CsrfProvider>
      <Component {...pageProps} />
    </CsrfProvider>
  );
}

5. Send the token

Use csrfFetch from the hook; it adds the token header and picks up rotated tokens from responses:

'use client'; // App Router only
import { useCsrf } from '@csrf-armor/nextjs/client';

export function ContactForm() {
  const { csrfToken, csrfFetch } = useCsrf();

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    await csrfFetch('/api/contact', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: data.get('message') }),
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <textarea name="message" required />
      <button type="submit" disabled={!csrfToken}>Send</button>
    </form>
  );
}

API routes need no extra code: the middleware has already validated the request before your handler runs.

Server Actions

Include the token as a hidden field. The action must declare its FormData parameter, even if unused, because Next.js only sends declared arguments and the token travels in the form data:

'use client';
import { useCsrf } from '@csrf-armor/nextjs/client';
import { saveMessage } from './actions';

export function MessageForm() {
  const { csrfToken } = useCsrf();
  return (
    <form action={saveMessage}>
      <input type="hidden" name="csrf_token" value={csrfToken ?? ''} />
      <input name="message" />
      <button type="submit">Save</button>
    </form>
  );
}
// actions.ts
'use server';

export async function saveMessage(_formData: FormData) {
  // Only runs if the middleware accepted the token
}

Client API

Import from @csrf-armor/nextjs/client.

<CsrfProvider config?>

Keeps the token in React state, re-reads it on route changes and back/forward navigation, and updates it from response headers.

config optionDefaultDescription
cookieName'csrf-token'Cookie to read the token from. Match cookie.name on the server.
headerName'x-csrf-token'Header to send the token in. Match token.headerName on the server.
initialTokennoneToken to start with, e.g. rendered by the server.
refreshEndpointcurrent pathURL fetched to obtain a fresh token.

useCsrf()

Returns { csrfToken, csrfFetch, updateToken }:

  • csrfToken: string | null: the current token
  • csrfFetch(input, init?): fetch that sends the token header and stores any new token from the response
  • updateToken(): re-read the token from the cookie

Throws if used outside CsrfProvider.

Different strategies per route

Create one protector per strategy and choose per request:

const apiCsrf = createCsrfMiddleware({ strategy: 'signed-token', secret: process.env.CSRF_SECRET });
const webCsrf = createCsrfMiddleware({ secret: process.env.CSRF_SECRET });

export async function middleware(request: NextRequest) {
  const protect = request.nextUrl.pathname.startsWith('/api/') ? apiCsrf : webCsrf;
  const result = await protect(request, NextResponse.next());
  return result.success
    ? result.response
    : NextResponse.json({ error: 'CSRF validation failed' }, { status: 403 });
}

Give each protector a different cookie.name if both can apply to the same browser.

Configuration

createCsrfMiddleware() accepts the shared CsrfConfig. All options are optional; secret is required in production.

A complete example app, including an attacker page for testing each strategy, lives in examples/nextjs-app.

License

MIT © Muneeb Samuels

版本与发布记录

@csrf-armor/nextjs 共发布 19 个版本,首次发布于 2025/06/03;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.4.8latest2026/10/061 个月前
1.4.72026/10/051 个月前
1.4.62026/10/041 个月前
1.4.52026/08/073 个月前
1.4.42026/04/226 个月前
1.4.32026/04/226 个月前

关于 @csrf-armor/nextjs 的常见问题

@csrf-armor/nextjs 是什么?

CSRF protection middleware for Next.js applications

如何安装 @csrf-armor/nextjs?

在项目目录运行 npm install @csrf-armor/nextjs,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:next(^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0)、react(^18.2.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@csrf-armor/nextjs 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@csrf-armor/nextjs 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@csrf-armor/nextjs 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@csrf-armor/nextjs 可以商用吗?

@csrf-armor/nextjs 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@csrf-armor/nextjs 的下载量有多少?

根据 npm 官方下载统计,@csrf-armor/nextjs 在 2026/10/11 – 2026/11/09 这 30 天内被下载 21,455 次,日均约 715 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@csrf-armor/nextjs 还在维护吗?

最新版本 1.4.8 发布于 2026/10/06(1 个月前);至今共发布 19 个版本,其中过去 12 个月发布了 8 个;首次发布于 2025/06/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。