feat(next-csrf): modernize for Next.js 16 and React 19#35
feat(next-csrf): modernize for Next.js 16 and React 19#35riceharvest wants to merge 71 commits intomainfrom
Conversation
- Upgraded multiple packages to modern standards (Next.js, Next-auth, PWA, SEO). - Added new utility packages: critters, next-circuit-breaker, next-csrf, next-images, next-json-ld. - Integrated Changesets for versioning. - Updated CI/CD workflows and linting configurations. - Fixed numerous linting and type-checking issues across the monorepo.
- Remove legacy NextAuth adapters and resolve workspace version conflicts - Clean up test warning noise and fix tsconfig/jest setups for next-auth - Update Workbox/Terser dependencies in next-pwa to align with workspace - Synchronize root lockfile to reflect nested package resolutions
Fixes `JWT_AUTO_GENERATED_SIGNING_KEY` and `JWT_AUTO_GENERATED_ENCRYPTION_KEY` warnings properly by supplying JWKs directly in the test suite rather than mocking the logger.
Review Summary by QodoModernize monorepo for Next.js 16, React 19, and Web API support with enhanced security and comprehensive testing
WalkthroughsDescription• **Modernized CSRF package for Next.js 16 and React 19**: Added verifyCsrfToken() for App Router with async headers() and cookies() support, enhanced token validation with multiple sources, and separated httpOnly settings for secret and token cookies • **Extended session utilities for Web API support**: Added getWebSession() function for Web API Request/Response objects, refactored decorateSession() with callbacks, enhanced parseTime() with duration units, and improved commitHeader() for both Node.js and Web API • **Enhanced next-connect middleware execution**: Improved error handling for multiple next() calls and proper async/await handling with promise tracking • **Modernized OAuth implementation**: Removed external oauth package dependency, replaced with native fetch API implementation for OAuth 2.x • **Added TypeORM and Prisma legacy adapters**: Comprehensive implementations for next-auth with full CRUD operations and backward compatibility • **Improved security and robustness**: Fixed CSS inlining vulnerabilities, enhanced URL sanitization, improved container detection in critters package • **Extended test coverage**: Added comprehensive tests for CSRF middleware, App Router verification, Web API sessions, MDX functionality, compose plugins, and JWT operations • **Migrated test frameworks**: Transitioned multiple packages from Jest to Vitest and Node.js native test runner • **Added new packages and examples**: Implemented react-query-auth with Vite example, MDX utilities, and Mock Service Worker integration • **Simplified and modernized documentation**: Removed deprecation notices, updated JSDoc comments, cleaned up linting directives Diagramflowchart LR
CSRF["CSRF Package<br/>Modernization"]
Session["Session Package<br/>Web API Support"]
Connect["next-connect<br/>Error Handling"]
Auth["next-auth<br/>OAuth & Adapters"]
Tests["Test Framework<br/>Migrations"]
Security["Security<br/>Improvements"]
CSRF -- "App Router<br/>verification" --> NextJS["Next.js 16<br/>Support"]
Session -- "Web API<br/>Request/Response" --> NextJS
Connect -- "Async<br/>middleware" --> NextJS
Auth -- "Native OAuth<br/>implementation" --> NextJS
Tests -- "Vitest &<br/>Node.js test" --> Quality["Code Quality"]
Security -- "URL sanitization<br/>& validation" --> Quality
File Changes1. packages/next-images/test/index.test.ts
|
Code Review by Qodo
1. tsup externals cleared
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8485cab843
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
packages/next-csrf/package.json
Outdated
| "cookie": "^1.1.1", | ||
| "cookie-signature": "^1.2.2", | ||
| "csrf": "^3.1.0", | ||
| "next": "^16.1.6" |
There was a problem hiding this comment.
Keep Next.js as a peer-only dependency
Move next out of dependencies, because this line forces every consumer to install a private Next 16 copy even when their app is on another supported peer version (for example Next 13/14). Since this package also declares next as a peer and imports next/headers, the extra nested install can bind runtime resolution to the wrong Next instance and create version-skew build/runtime failures that are very hard to diagnose.
Useful? React with 👍 / 👎.
| */`, | ||
| }; | ||
| }, | ||
| external: [], |
There was a problem hiding this comment.
1. tsup externals cleared 📘 Rule violation ⛯ Reliability
packages/next-csrf/tsup.config.ts now sets external: [], which can unintentionally bundle framework/runtime dependencies and change build outputs for consumers. This risks breaking established package-local build behavior.
Agent Prompt
## Issue description
`packages/next-csrf/tsup.config.ts` cleared the `external` list (`external: []`). This can cause bundling of dependencies that were previously externalized, potentially breaking consumer builds or runtime expectations.
## Issue Context
The monorepo compliance rules require preserving package-local tooling configuration compatibility.
## Fix Focus Areas
- packages/next-csrf/tsup.config.ts[3-13]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| // @vitest-environment happy-dom | ||
| import React from "react" | ||
| import { http, HttpResponse } from "msw" | ||
| import { useState } from "react" | ||
| import userEvent from "@testing-library/user-event" | ||
| import { render, screen, waitFor } from "@testing-library/react" | ||
| import { server, mockProviders } from "./helpers/mocks" |
There was a problem hiding this comment.
2. providers.test.jsx not formatted 📘 Rule violation ✓ Correctness
Modified code in packages/next-auth/src/client/__tests__/providers.test.jsx uses double quotes and appears to omit semicolons, conflicting with Prettier conventions. This introduces inconsistent formatting in tests.
Agent Prompt
## Issue description
`packages/next-auth/src/client/__tests__/providers.test.jsx` includes formatting that conflicts with the repository’s Prettier conventions.
## Issue Context
Prettier conventions are required across the monorepo for consistency.
## Fix Focus Areas
- packages/next-auth/src/client/__tests__/providers.test.jsx[1-34]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| "dependencies": { | ||
| "cookie": "^1.1.1", | ||
| "cookie-signature": "^1.2.2", | ||
| "csrf": "^3.1.0", | ||
| "next": "^16.1.6" | ||
| } |
There was a problem hiding this comment.
3. Next shipped as dependency 🐞 Bug ⛯ Reliability
@opensourceframework/next-csrf now lists next in dependencies (while also in peerDependencies), which can install a nested Next.js copy instead of using the host app’s Next.js. This can create version conflicts and runtime/tooling breakage when the host app uses a different Next version.
Agent Prompt
### Issue description
`@opensourceframework/next-csrf` declares `next` in both `peerDependencies` and `dependencies`. This can lead to a nested Next.js installation and version conflicts in consuming apps.
### Issue Context
The package already targets Next.js consumers via `peerDependencies`; shipping `next` as a runtime dependency is likely unintended and risky.
### Fix Focus Areas
- packages/next-csrf/package.json[59-81]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| ```typescript | ||
| // lib/csrf.ts | ||
| import { nextCsrf } from '@opensourceframework/next-csrf'; | ||
| // Usage example | ||
| import { createCSRF } from '@opensourceframework/next-csrf'; | ||
|
|
||
| const { csrf, setup } = nextCsrf({ | ||
| // Required: A secret key for signing cookies (use environment variable in production) | ||
| const csrf = createCSRF({ | ||
| 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 }; | ||
| // Use in API routes | ||
| export default csrf.protect(handler); | ||
| ``` |
There was a problem hiding this comment.
4. Readme documents wrong api 🐞 Bug ✓ Correctness
packages/next-csrf/README.md documents createCSRF / csrf.protect and a default tokenKey of _csrf, but the package’s actual public entrypoint exports nextCsrf and defaults tokenKey to XSRF-TOKEN. Users following the README will write imports/calls that fail and configure the wrong cookie/header names.
Agent Prompt
### Issue description
The README documents a `createCSRF` / `csrf.protect` API and `_csrf` defaults that do not match the actual package exports/defaults.
### Issue Context
The package entrypoint exports `nextCsrf` and defaults `tokenKey` to `XSRF-TOKEN`. The README should not instruct users to import symbols that aren’t exported.
### Fix Focus Areas
- packages/next-csrf/README.md[37-103]
- packages/next-csrf/src/index.ts[32-72]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
|
3 similar comments
|
|
|
|
|
|
…support - Remove 'next' from dependencies to avoid nested copy (already in peerDependencies) - Add 'csrf-token' header to verifyCsrfToken for consistency with Pages Router middleware
Code Review SummaryStatus: No Issues Found | Recommendation: Merge Overview
Files Reviewed (2 files)
|
|
|
|
Superseded by #59 (squash merge of all modernization PRs). Changes included in main. |
Closes #22 (roadmap).
verifyCsrfTokenworks with Next.js 16 asynccookies()andheaders().reactandreact-domaspeerDependencies.nextversion range inpeerDependencies.