Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions packages/vinext/src/shims/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -547,16 +547,24 @@ const Link = forwardRef<HTMLAnchorElement, LinkProps>(function Link(

// Block dangerous URI schemes (javascript:, data:, vbscript:).
// Render an inert <a> without href to prevent XSS while preserving
// styling and attributes like className, id, aria-*.
// styling, refs, and developer event handlers like onClick.
// This check is placed after all hooks to satisfy the Rules of Hooks.
if (isDangerous) {
if (process.env.NODE_ENV !== "production") {
console.warn(`<Link> blocked dangerous href: ${resolvedHref}`);
}
return (
<a {...anchorProps} onMouseEnter={handleMouseEnter} onTouchStart={handleTouchStart}>
{children}
</a>
<LinkStatusContext.Provider value={linkStatusValue}>
<a
ref={setRefs}
onClick={onClick}
onMouseEnter={handleMouseEnter}
onTouchStart={handleTouchStart}
{...anchorProps}
>
{children}
</a>
</LinkStatusContext.Provider>
);
}

Expand Down
17 changes: 17 additions & 0 deletions tests/e2e/app-router/nextjs-compat/javascript-urls.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,21 @@ test.describe("javascript-urls", () => {
await page.locator('a[href="/nextjs-compat/javascript-urls/safe"]').click();
await expect(page).toHaveURL(`${BASE}/nextjs-compat/javascript-urls/safe`);
});

// Next.js keeps user-provided Link onClick handlers on anchors whose href is
// later blocked by React/Next.js javascript: URL protections.
// Reference implementation: https://github.com/vercel/next.js/blob/canary/packages/next/src/client/link.tsx
test("preserves custom Link onClick handlers when blocking unsafe hrefs", async ({ page }) => {
await page.goto(`${BASE}/nextjs-compat/javascript-urls/link-onclick`);
await waitForAppRouterHydration(page);
const initialUrl = page.url();

const unsafeLink = page.locator("#unsafe-link");
await expect(unsafeLink).not.toHaveAttribute("href", /.+/);

await unsafeLink.click();

await expect(page.locator("#click-count")).toHaveText("clicks: 1");
expect(page.url()).toBe(initialUrl);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use client";

import { useState } from "react";
import Link from "next/link";
import { DANGEROUS_JAVASCRIPT_URL } from "../bad-url";

export default function Page() {
const [clicks, setClicks] = useState(0);

return (
<>
<p id="click-count">clicks: {clicks}</p>
<Link
id="unsafe-link"
href={DANGEROUS_JAVASCRIPT_URL}
onClick={() => {
setClicks((value) => value + 1);
}}
>
unsafe link with custom click handler
</Link>
</>
);
}
Loading