@edge-csrf/nextjs

中文文档
2.5.3-cloudflare-rc1发布于 2024/11/21MITTypeScriptESM + CJS零依赖近 30 天下载 18.8万

Edge-CSRF Next.js integration library

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

原始使用文档
文档目录10 节
  1. Quickstart
  2. App Router
  3. Pages Router
  4. Examples
  5. Lower-level implementations
  6. Configuration
  7. API
  8. Types
  9. Classes
  10. Methods

Next.js

This is the documentation for Edge-CSRF's Next.js integration. The integration works with Next.js 13, 14 and 15.

Quickstart

First, add the integration library as a dependency to your app:

npm install @edge-csrf/nextjs
# or
pnpm add @edge-csrf/nextjs
# or
yarn add @edge-csrf/nextjs

Next, create a middleware file (middleware.ts) for your project and add the Edge-CSRF middleware:

// middleware.ts

import { createCsrfMiddleware } from '@edge-csrf/nextjs';

// initalize csrf protection middleware
const csrfMiddleware = createCsrfMiddleware({
  cookie: {
    secure: process.env.NODE_ENV === 'production',
  },
});

export const middleware = csrfMiddleware;

Now, all HTTP submission requests (e.g. POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token. To add the CSRF token to your forms, you can fetch it from the X-CSRF-Token HTTP response header server-side or client-side. For example:

App Router

// app/page.tsx

import { headers } from 'next/headers';

export default async function Page() {
  const h = await headers();
  const csrfToken = h.get('X-CSRF-Token') || 'missing';

  return (
    <form action="/api/form-handler" method="post">
      <input type="hidden" value={csrfToken}>
      <input type="text" name="my-input">
      <input type="submit">
    </form>
  );
}
// app/form-handler/route.ts

import { NextResponse } from 'next/server';

export async function POST() {
  return NextResponse.json({ status: 'success' });
}

Pages Router

// pages/form.ts

import type { NextPage, GetServerSideProps } from 'next';
import React from 'react';

type Props = {
  csrfToken: string;
};

export const getServerSideProps: GetServerSideProps = async ({ res }) => {
  const csrfToken = res.getHeader('x-csrf-token') || 'missing';
  return { props: { csrfToken } };
}

const FormPage: NextPage<Props> = ({ csrfToken }) => {
  return (
    <form action="/api/form-handler" method="post">
      <input type="hidden" value={csrfToken}>
      <input type="text" name="my-input">
      <input type="submit">
    </form>
  );
}

export default FormPage;
// pages/api/form-handler.ts

import type { NextApiRequest, NextApiResponse } from 'next';

type Data = {
  status: string
};

export default function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
  // this code won't execute unless CSRF token passes validation
  res.status(200).json({ status: 'success' });
}

Examples

Here are some examples in this repository:

VersionRouterImplementation
Next.js 13app routerHTML form
Next.js 13app routerJavaScript (dynamic)
Next.js 13app routerJavaScript (static)
Next.js 13pages routerHTML form
Next.js 14app routerHTML form
Next.js 14app routerJavaScript (dynamic)
Next.js 14app routerJavaScript (static)
Next.js 14app routerSentry
Next.js 14app routerServer action (form)
Next.js 14app routerServer action (non-form)
Next.js 14pages routerHTML form
Next.js 15app routerHTML form
Next.js 15app routerJavaScript (dynamic)
Next.js 15app routerJavaScript (static)
Next.js 15app routerSentry
Next.js 15app routerServer action (form)
Next.js 15app routerServer action (non-form)
Next.js 15pages routerHTML form

Lower-level implementations

If you want lower-level control over the response or which routes CSRF protection will be applied to you can use the createCsrfProtect() method to create a function that you can use inside your own custom middleware:

// middleware.ts

import { CsrfError, createCsrfProtect } from '@edge-csrf/nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// initalize csrf protection method
const csrfProtect = createCsrfProtect({
  cookie: {
    secure: process.env.NODE_ENV === 'production',
  },
});

// Next.js middleware function
export const middleware = async (request: NextRequest) => {
  const response = NextResponse.next();

  try {
    await csrfProtect(request, response);
  } catch (err) {
    if (err instanceof CsrfError) return new NextResponse('invalid csrf token', { status: 403 });
    throw err;
  }

  return response;
};

Configuration

// default config

{
  cookie: {
    name: '_csrfSecret',
    path: '/',
    maxAge: undefined,
    domain: '',
    secure: true,
    httpOnly: true,
    sameSite: 'strict'
  },
  excludePathPrefixes: ['/_next/'],
  ignoreMethods: ['GET', 'HEAD', 'OPTIONS'],
  saltByteLength: 8,
  secretByteLength: 18,
  token: {
    fieldName: 'csrf_token',
    responseHeader: 'X-CSRF-Token',
    value: undefined
  }
}

API

The following are named exports in the the @edge-csrf/nextjs module:

Types

NextCsrfProtect - A function that implements CSRF protection for Next.js requests

  * @param {NextRequest} request - The Next.js request instance
  * @param {NextResponse} response - The Next.js response instance
  * @returns {Promise<void>} - The function completed successfully
  * @throws {CsrfError} - The function encountered a CSRF error

Classes

CsrfError - A class that inherits from Error and represents CSRF errors

Methods

createCsrfMiddleware([, options]) - Create a new instance of Next.js middleware

  * @param {object} options - The configuration options
  * @returns {Middleware} - The middleware

createCsrfProtect([, options]) - Create a lower-level function that can be used inside Next.js middleware
                                 to implement CSRF protection for requests

  * @param {object} options - The configuration options
  * @returns {NextCsrfProtect} - The CSRF protection function

版本与发布记录

@edge-csrf/nextjs 共发布 23 个版本,首次发布于 2024/04/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.5.3-cloudflare-rc1latest2024/11/212 年前
2.5.2-rc12024/11/212 年前
2.5.22024/10/252 年前
2.5.12024/10/232 年前
2.5.02024/09/222 年前
2.4.02024/09/222 年前

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

@edge-csrf/nextjs 是什么?

Edge-CSRF Next.js integration library注意:该包已被作者标记为弃用——Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

如何安装 @edge-csrf/nextjs?

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

@edge-csrf/nextjs 支持 TypeScript 吗?

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

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

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

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

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

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

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

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

最新版本 2.5.3-cloudflare-rc1 发布于 2024/11/21(2 年前);至今共发布 23 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/04/20。作者已将其标记为弃用,新项目建议寻找替代方案。