
Security News
US Government Forces Anthropic to Pull Claude Fable Days After Launch
Anthropic says the directive cited national security concerns over a narrow jailbreak, but offered no specific technical details.
@opensourceframework/next-csrf
Advanced tools
CSRF protection for Next.js applications - Maintained fork of next-csrf
CSRF protection for Next.js applications
This is a maintained fork of the original next-csrf package by Juan Olvera (j0lv3r4). The original package was last updated in April 2023 and has been archived. This fork continues maintenance with updates for Next.js 14-16 support and TypeScript improvements.
# npm
npm install @opensourceframework/next-csrf
# yarn
yarn add @opensourceframework/next-csrf
# pnpm
pnpm add @opensourceframework/next-csrf
// lib/csrf.ts
import { nextCsrf } from '@opensourceframework/next-csrf';
const { csrf, setup } = nextCsrf({
// Required: A secret key for signing cookies (use environment variable in production)
secret: process.env.CSRF_SECRET,
// Optional: Customize the token cookie name (default: 'XSRF-TOKEN')
tokenKey: 'XSRF-TOKEN',
// Optional: Custom error message (default: 'Invalid CSRF token')
csrfErrorMessage: 'Invalid CSRF token',
// Optional: Methods to ignore (default: ['GET', 'HEAD', 'OPTIONS'])
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
// Optional: Cookie options
cookieOptions: {
httpOnly: true,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
},
});
export { csrf, setup };
For Pages Router:
// pages/login.tsx
import { setup } from '../lib/csrf';
function LoginPage() {
const handleSubmit = async (event) => {
event.preventDefault();
const response = await fetch('/api/protected', {
method: 'POST',
});
if (response.ok) {
console.log('Request succeeded with CSRF protection');
}
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
// Setup CSRF tokens on this page
export const getServerSideProps = setup(async ({ req, res }) => {
return { props: {} };
});
export default LoginPage;
// pages/api/protected.ts
import { csrf } from '../../lib/csrf';
import type { NextApiRequest, NextApiResponse } from 'next';
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(200).json({
message: 'This API route is protected with CSRF!'
});
};
export default csrf(handler);
nextCsrf(options)Creates CSRF middleware functions.
Parameters:
| Option | Type | Default | Description |
|---|---|---|---|
secret | string | - | Secret key for signing cookies. Recommended for production. |
tokenKey | string | 'XSRF-TOKEN' | Name of the CSRF token cookie. |
csrfErrorMessage | string | 'Invalid CSRF token' | Error message for invalid tokens. |
ignoredMethods | string[] | ['GET', 'HEAD', 'OPTIONS'] | HTTP methods to skip CSRF validation. |
cookieOptions | CookieSerializeOptions | See below | Cookie serialization options. |
Default Cookie Options:
{
httpOnly: true,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
}
Returns:
An object with two middleware functions:
setup - Middleware to create and set CSRF tokenscsrf - Middleware to validate CSRF tokenssetup(handler)Middleware that creates CSRF secret and token cookies.
req, res) and getServerSideProps (context)csrfSecret and the token cookie (default: XSRF-TOKEN)secret option is provided, the token is signedcsrf(handler)Middleware that validates CSRF tokens on incoming requests.
secret was providedHttpErrorCustom error class for CSRF-related HTTP errors.
import { HttpError } from '@opensourceframework/next-csrf';
throw new HttpError(403, 'Custom error message');
next-csrfIf you're migrating from the original next-csrf package:
- import { nextCsrf } from 'next-csrf';
+ import { nextCsrf } from '@opensourceframework/next-csrf';
- "next-csrf": "^0.2.1"
+ "@opensourceframework/next-csrf": "^0.2.2"
The API is fully compatible with the original package.
Always use a secret in production: Set secret to a cryptographically secure random string.
Use HTTPS in production: Set secure: true in cookie options for production environments.
Regenerate tokens: The middleware automatically regenerates tokens after each validated request.
Session invalidation: If you change the secret, all existing sessions will be invalidated.
Cookie settings: The default settings (httpOnly: true, sameSite: 'lax') provide good baseline security.
The package implements the Synchronizer Token Pattern:
Setup Phase: When a user visits a page with CSRF setup, the middleware:
Validation Phase: When a user submits a request:
# Install dependencies
pnpm install
# Build the package
pnpm build
# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Type checking
pnpm typecheck
MIT License - See LICENSE for details.
Contributions are welcome! Please read the contributing guidelines first.
FAQs
CSRF protection for Next.js applications - Maintained fork of next-csrf
The npm package @opensourceframework/next-csrf receives a total of 22 weekly downloads. As such, @opensourceframework/next-csrf popularity was classified as not popular.
We found that @opensourceframework/next-csrf demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Anthropic says the directive cited national security concerns over a narrow jailbreak, but offered no specific technical details.

Security News
A network of 152 Chrome live wallpaper extensions hid ad tracking and made extension-driven traffic look like Google search clicks.

Company News
Socket’s first CISO brings deep experience securing high-growth SaaS companies as open source supply chain threats accelerate.