Skip to main content
Back to contributions
Pull Request
Open
55.9K

Fix improperly escaped code block in MDXError message

withastro/astro

Fixed greedy regex in error message rendering that caused markdown link examples to consume extra characters

The Problem

When using auto-linked URLs in MDX files (syntax: <https://example.com>), Astro correctly throws an error since this markdown syntax does not work in MDX. However, the error message was improperly escaped and garbled.

Broken error message:

Unexpected character / (U+002F) before local name, expected a character that can start a name, such as a letter, $, or _ (note: to create a link in MDX, use [text](http://localhost:4321/url)%3C/code%3E)

The markdown link syntax [text](url) at the end was getting incorrectly rendered as a clickable “text” link pointing to a malformed URL instead of being displayed as literal example text.

The bug was in the renderErrorMarkdown function at packages/astro/src/core/errors/dev/utils.ts. The regex for matching markdown links was using a greedy quantifier:

const linkRegex = /\[([^[]+)\]\((.*)\)/g;
//                              ^^^ greedy - matches too much!

The (.*) captures everything up to the last ) in the string, not the first one after the URL. When an error message contains [text](url)</code>), the regex incorrectly captures url)</code> as the URL.

The Solution

I changed the regex to exclude ) from the URL capture group, making it stop at the first closing parenthesis:

const linkRegex = /\[([^[]+)\]\(([^)]*)\)/g;
//                              ^^^^^^ non-greedy - stops at first )

Before implementing the fix, I wrote 13 unit tests for the renderErrorMarkdown function to verify the hypothesis and ensure existing functionality wouldn’t break. Two tests failed as expected with the buggy regex, confirming the root cause. After applying the fix, all tests passed.

Files Changed

FileChange
packages/astro/src/core/errors/dev/utils.tsFixed greedy regex in linkRegex
packages/astro/test/units/errors/dev-utils.test.jsAdded 13 tests for renderErrorMarkdown

Test Coverage

The new test suite covers:

  • Basic markdown link to HTML anchor conversion
  • Bold text and inline code rendering
  • Bare URL detection and linking
  • HTML entity escaping
  • Links followed by closing parentheses (the bug case)
  • Escaped HTML followed by link syntax (MDX error message case)
  • Multiple links in the same message
  • CLI output formatting

Timeline

DateEvent
Dec 21, 2025Issue #15068 opened by @kylejrp
Jan 16, 2026Claimed issue and started investigation
Jan 16, 2026Identified root cause and wrote tests to verify hypothesis
Jan 16, 2026Implemented fix and submitted PR #15230