21 Commits

Author SHA1 Message Date
James Anderson 7fdcdd3c69 feat(og): add @next/og / @vercel/og support with Cloudflare Workers compatibility (#356)
* feat(og): add @next/og support with Cloudflare Workers compatibility

- Add vinext:og-font-fix transform plugin that patches @vercel/og/dist/index.edge.js
  at Vite transform time: inlines the fallback font as base64 (avoids fetch() with
  import.meta.url which breaks in workerd) and defers WASM init to first use (avoids
  WebAssembly.instantiate() being blocked in Node.js module runner)
- Add @vercel/og to optimizeDeps.exclude so Vite's esbuild pre-bundler doesn't cache
  the module before the transform hook runs
- Add vinext:og-assets build plugin that copies font/WASM assets to RSC output dir
- Add /app/api/og route to app-router-cloudflare example and app-basic fixture
- Add shared Playwright e2e spec (tests/e2e/og-image.spec.ts) asserting PNG validity,
  correct 1200x630 dimensions, param-driven content, and determinism
- Register og-image.spec.ts in app-router, cloudflare-workers, and cloudflare-dev
  Playwright projects (18 tests total, all passing)

* refactor(og): generalize fetch+import.meta.url asset inlining, drop WASM lazy-init patch

Replace the @vercel/og-specific vinext:og-font-fix plugin with a general
vinext:og-inline-fetch-assets plugin that:

- Matches ANY fetch(new URL('./asset', import.meta.url)).then(res => res.arrayBuffer())
  pattern, not just the hardcoded noto-sans filename
- Resolves each asset relative to the module's on-disk path (via the transform id)
  and inlines it as base64 — works for any font version or additional assets
- Applies to any library using this pattern, not just @vercel/og

Also removes the WASM lazy-init patch: now that @vercel/og is in optimizeDeps.exclude,
the module runs through workerd (not the Node.js pre-bundler cache) where
WebAssembly.instantiate() works fine. The lazy-init workaround was only needed
when the pre-bundler cache bypassed the transform hook.

The og-assets build plugin is updated to only copy resvg.wasm (not the font,
which is now inlined and will no longer appear in the bundle by filename).

* fix(og): inline readFileSync assets from @vercel/og node build

The production RSC bundle resolves @vercel/og under the 'import' export
condition, getting dist/index.node.js instead of dist/index.edge.js.
The node build loads font and WASM via fs.readFileSync(fileURLToPath(
new URL('./file', import.meta.url))), which breaks after bundling because
import.meta.url points to the bundle output file, not the dist/ dir.

Extend vinext:og-inline-fetch-assets with a second regex pattern that
matches readFileSync(fileURLToPath(new URL(...))) and replaces it with
Buffer.from('<base64>', 'base64'), inlining both noto-sans font and
resvg.wasm at transform time. This eliminates the ENOENT errors seen
in the production build CI tests.

* refactor(og): address code review feedback

- Remove Fix 1 (font inlining) from vinext:og-font-patch — it was dead
  code since vinext:og-inline-fetch-assets (earlier in the plugin array)
  already handles the same fetch(new URL(...)) pattern generically. Only
  Fix 2 (yoga WASM extraction) remains in og-font-patch.

- Use split().join() instead of String.replace() in both Pattern 1 and
  Pattern 2 loops of og-inline-fetch-assets. String.replace(string, ...)
  only replaces the first occurrence; split().join() replaces all of them,
  which matters for libraries that may use the same pattern multiple times.

* refactor(og): use replaceAll instead of split().join()
2026-03-08 20:50:10 +00:00
James Anderson a5d65b851f test: add a fixme for middleware invocation count tracking (#350)
* test: add a fixme for middleware invocation count tracking

* test: clarify why registerCalled uses ESM live binding not globalThis
2026-03-08 15:19:54 +00:00
James Anderson 53257a8630 fix: layout not receiving correct params (#348)
* fix: layout not receiving correct params

* fix: layout not getting correct params on 404
2026-03-08 14:59:06 +00:00
James Anderson 4e0294fc4f fix: middleware crash in dev mode with cloudflare plugin (#344)
* test: middleware with cloudflare plugin and routing bypass

* fix: use module runner for pages middleware

* add pages router dev test
2026-03-08 14:04:11 +00:00
James Anderson f27796b922 fix: don't intercept requests in connect handler when cloudflare plugin is present (#343)
* test: assert App Router wins over Pages Router connect handler with cloudflare plugin

* update req.url with url
2026-03-08 10:28:09 +00:00
James Anderson c4c67fa5f4 fix: pages router instrumentation error reporting for api routes (#334)
* test: pages router instrumentation

* fix error handling

* add pages route to app dir

* fix api route type
2026-03-07 23:22:13 +00:00
James Anderson 80acf27933 fix: register instrumentation in rsc entry and put error handler in global scope (#330)
* test: instrumentation

* store onRequestError on globalThis

* add instrumentation registration app-dev-server

* guard against double calling runinstrumentation for appdir
2026-03-07 22:40:27 +00:00
Nathan Nguyen a78266481b feat: support export const revalidate on App Router GET route handlers (#320)
* chore: add .worktrees/ to gitignore

* feat: support `export const revalidate` on App Router GET route handlers

Read the route segment config `revalidate` from route handler modules
and set `Cache-Control: s-maxage=N, stale-while-revalidate` on GET
responses, matching Next.js behavior. Only applies when the handler
does not set its own Cache-Control header.

Unskip two E2E fixme cases and add vitest coverage.

* fix: guard revalidate=0 and add proper test fixtures

- Skip Cache-Control injection when revalidate is 0 (means "never cache")
- Add /api/custom-cache fixture that sets its own Cache-Control header
- Add /api/no-cache fixture with revalidate=0
- Fix "does not override" test to use a fixture that actually sets Cache-Control
- Add revalidate=0 test case
2026-03-07 17:10:25 +00:00
James Anderson 8cd07c29d9 fix: override next.config.js headers with middleware headers (#268)
* implement dangerous.middlewareHeadersOverrideNextConfigHeaders from opennext

* fix: preserve multi-value set-cookie in RSC middleware header merge, separate timing comment

* fix: accumulate Vary header in RSC middleware merge to preserve RSC, Accept

* Update packages/vinext/src/server/app-dev-server.ts
2026-03-07 15:05:02 +00:00
James Anderson cf60485fe3 fix: static-prefix routes not outranking dynamic catch-alls in route scoring (#275)
* fix: static-prefix routes not outranking dynamic catch-alls in route scoring

* share route precedence logic between app and pages router

* fix(routing): static-prefix boost collapsed infix-static ordering to a tie

* extra comment
2026-03-06 00:25:54 +00:00
James Anderson af30c7438e fix: config redirects not applying to rsc requests (#255)
* fix: config redirects not applying to rsc requests

* fix poorly written test

* add better fix for soft nav url diffs

* escape the .

* fix: strip .rsc from beforeFiles rewrites; fix redirect recursion and double pushState
2026-03-05 22:41:44 +00:00
Nathan Nguyen 706f40be0d fix: register MDX plugin at top level to fix transform ordering (#160)
* fix: register MDX plugin at top level to fix transform ordering

Plugins returned from the config() hook run after vite:import-analysis,
so @mdx-js/rollup transforms never fire. Move MDX to a top-level proxy
plugin with enforce:"pre" that delegates to the lazily-created MDX
instance once config() populates it.

Fixes #77

* address review: add config proxy, remove dead resolveId, fix comment separation

- Replace resolveId proxy with config proxy: @mdx-js/rollup has no
  resolveId hook, but its config() hook initializes format-aware
  processors with the Vite mode (development vs production). Without
  forwarding config(), MDX always compiles in production mode.
- Remove dead resolveId proxy (dead code, @mdx-js/rollup has no such hook)
- Separate MDX proxy comment from vinext:react-canary comment
- Update test to verify config and transform hooks on the proxy

* add E2E test for MDX import transform ordering

A regular page.tsx imports content.mdx as a React component and
renders it. This verifies the vinext:mdx proxy plugin transforms
.mdx files before vite:import-analysis runs (the core fix from #77).

---------

Co-authored-by: Steve Faulkner <sfaulkner@cloudflare.com>
2026-03-04 22:47:28 +00:00
Steve Faulkner 6f1902201d fix: use exact heading locator in next/dynamic E2E to fix flaky test (#209) 2026-03-01 07:53:54 -06:00
tomasgferreira 3d8aed9868 fix(config): respect has/missing conditions in next.config headers (#48)
* fix(config): respect has/missing conditions in next.config headers

Adds has/missing condition support to matchHeaders, wires request context
through dev/prod paths, updates NextHeader types, and adds unit + e2e tests
for header/cookie/query conditions.

* chore: add backward-compat comment for optional ctx in matchHeaders

Addresses review feedback: clarify that when no request context is
passed, has/missing conditions are silently skipped for backward
compatibility with existing callers.

* fix: wire has/missing conditions through redirects and rewrites in Pages Router dev

Pages Router dev was the only path missing has/missing support for
redirects and rewrites. The reqCtx was already being built for headers,
so hoist it and pass it to applyRedirects and applyRewrites too.

Also refactors applyRedirects and applyRewrites to delegate to the
shared matchRedirect/matchRewrite functions, eliminating duplicated
pattern-matching logic (same dedup pattern used for applyHeaders).

---------

Co-authored-by: tomoconstrutor <tomoconstrutor@gmail.com>
Co-authored-by: Steve Faulkner <sfaulkner@cloudflare.com>
2026-02-28 16:05:47 -06:00
Zeb Piasecki bcd4bb14cf feat: add CJS support via vite-plugin-commonjs (#198)
* feat: add CJS support via vite-plugin-commonjs

Add vite-plugin-commonjs to handle require() and module.exports in
both App Router and Pages Router. This enables CJS interop in server
components and pages, including CJS require('server-only') boundary
enforcement by @vitejs/plugin-rsc.

- Add vite-plugin-commonjs as a dependency and register it in the plugin array
- Add App Router fixtures: CJS basic, CJS server-only, CJS server-only
  violation (client component importing server-only module)
- Add Pages Router fixture: CJS basic (require/module.exports)
- Add integration tests for both routers (cjs.test.ts)
- Add App Router e2e tests for CJS rendering and server-only boundary
  enforcement (tests/e2e/app-router/cjs.spec.ts)
- Add Pages Router e2e test for CJS rendering
  (tests/e2e/pages-router/cjs.spec.ts)

* fix: use buildViteConfig() for Pages Router production builds

The Pages Router build path hardcoded plugins: [vinext()] in inline
config, duplicating plugins when a vite.config.ts also registers
vinext(). This caused double-transformation errors during production
builds. Use buildViteConfig() instead, matching the App Router path
which already handles this correctly.

* fix: move server-only-violation fixture to isolated directory

The server-only-violation fixture causes a fatal build error during
production builds of app-basic (the RSC plugin rejects the intentional
violation). This breaks unrelated tests in app-router.test.ts.

Move the fixture to tests/fixtures/app-cjs-violation/ so it doesn't
poison the shared app-basic production build. Remove the E2E test case
since it requires the app-basic dev server; the server-only boundary
enforcement for CJS require() is verified by the RSC plugin's build
validation.

* fix: address review feedback from bonk

- Remove unused components/random.tsx (dead code, Pages Router CJS test
  uses pages/cjs/random.ts instead)
- Add trailing newlines to fixture files
- Move commonjs() plugin earlier in array (after tsconfigPaths, before
  vinext:config) so CJS->ESM transform runs before directive scanning
- Tighten test assertions: use regex for 'Random:.*4' to be specific
  while handling React SSR comment nodes between text and expressions

---------

Co-authored-by: Steve Faulkner <sfaulkner@cloudflare.com>
2026-02-28 15:23:21 -06:00
ubugeeei 2c650ec089 feat: type aware linting with tsgolint (#38) 2026-02-27 07:37:12 +00:00
luo jiyin dff6da26af fix: correct various typos (#114)
* fix: typo filesytem -> filesystem

* fix: typo filesytem -> filesystem

* fix: typo filesytem -> filesystem

* fix: typo Overwite -> Overwrite

* fix: typo hypen -> hyphen
2026-02-26 21:31:20 -08:00
Sunil Pai 0e750f7934 Security hardening: redirect sanitization, header stripping, ALS isolation tests, and safer command execution (#105)
* Sanitize redirects/headers and use execFileSync

Replace execSync calls with execFileSync (pass argv arrays) to avoid shell interpolation and adjust package-install logic to split package manager and args. Sanitize redirect destinations in SSR paths to prevent protocol-relative open-redirects and use sanitizeDestinationLocal for Next.js redirects. Ensure middleware receives a cleaned pathname by stripping internal .rsc suffix before creating NextRequest and add a test for this behavior. Strip sensitive headers (cookie, authorization and x-middleware-*) from proxied external requests and add a test. Document cache key hazards for auth headers in fetch-cache, add a security note for dangerouslySetInnerHTML in head SSR, and set the Draft Mode cookie to include Secure in production (with tests for production/dev behavior).

* Rename middleware header to x-custom-middleware

Change middleware header name from x-middleware-test to x-custom-middleware across fixtures and tests, and clarify server comment about stripping x-middleware-* headers from responses (reserved for internal routing signals). Files updated: packages/vinext/src/server/prod-server.ts (comment tweak), tests/fixtures/pages-basic/middleware.ts (header set), and tests/pages-router.test.ts (expectations and test titles/comments). This ensures tests reflect the new public header name while preserving internal x-middleware-* semantics.

* Normalize leading slashes and strip headers

Normalize redirect/rewrite destinations by collapsing any leading slashes or backslashes to a single "/" to avoid protocol-relative redirects and handle browser-backslash behavior. Strip additional sensitive headers (x-api-key, proxy-authorization) from proxied requests and ensure all x-middleware-* internal headers are removed from responses (broadened from x-middleware-request-*). Update dev/server sanitization logic accordingly. Update tests and fixture middleware to use shortened x-mw-* header names and add tests covering backslash normalization.
2026-02-26 08:50:12 +00:00
Dane 98b243493f fix: resolve CodeQL security alerts (ReDoS, incomplete sanitization, bad code gen) (#87)
Refactor chained .replace() to single-pass tokenizers in pattern matching:
- matchConfigPattern in config-matchers.ts and index.ts
- escapeHeaderSource (new) replaces inline chained escaping in matchHeaders/applyHeaders
- matchMiddlewarePattern in prod server entry template
- matchPattern in middleware.ts

Also:
- escapeHeaderSource correctly handles :param(constraint) patterns
- Fix decodeURIComponent parity gap in index.ts matchConfigPattern
- Fix redundant dot in middleware.ts tokenizer char class
- Add lgtm suppression comments for false positives in test files
- Add unit tests for escapeHeaderSource
2026-02-26 00:18:46 -06:00
Sunil Pai 493a4c1b70 fix: add 'use client' to next/dynamic shim for App Router RSC compatibility (#7)
When a server component imports next/dynamic, the RSC serializer must
treat it as a client boundary. Without 'use client', the dynamic()
function executes inline in the RSC environment — for ssr:false, this
serializes null into the RSC payload and the client never loads the
component.

Adding 'use client' matches Next.js's App Router behavior where
next/dynamic is a client module. The RSC serializer emits a client
reference, and the client executes the full dynamic logic including
the ssr:false mount-on-client behavior.

Updated test fixtures that called dynamic() from server modules to
include 'use client' — this is required since dynamic() is now a
client export and can only be called from client modules.

Added E2E test for ssr:false from a server component page.
2026-02-24 11:13:29 -06:00
Steve Faulkner 12fea722b6 Initial public release of vinext 2026-02-24 09:29:39 -06:00