withastro/astro · error · Error

Failed to parse image reference: ${imagePath}

Error message

Failed to parse image reference: ${imagePath}

What it means

Thrown as a plain Error (no AstroError code) from updateImageReferencesInBody when processing a collected image reference embedded in rendered HTML. The wrapped try-block covers JSON.parse of the decoded attribute, imageSrcToImportId resolution, map lookup, and getImage() — any failure there surfaces as this generic message with the offending imagePath.

Source

Thrown at packages/astro/src/content/runtime.ts:492

			let image: GetImageResult;
			if (URL.canParse(decodedImagePath.src)) {
				// Remote image, pass through without resolving import
				// We know we should resolve this remote image because either:
				// 1. It was collected with the remark-collect-images plugin, which respects the astro image configuration,
				// 2. OR it was manually injected by another plugin, and we should respect that.
				image = await getImage(decodedImagePath);
			} else {
				const id = imageSrcToImportId(decodedImagePath.src, fileName);

				const imported = imageAssetMap.get(id);
				if (!id || imageObjects.has(id) || !imported) {
					continue;
				}
				image = await getImage({ ...decodedImagePath, src: imported });
			}
			imageObjects.set(imagePath, image);
		} catch {
			throw new Error(`Failed to parse image reference: ${imagePath}`);
		}
	}

	return html.replaceAll(CONTENT_LAYER_IMAGE_REGEX, (full, imagePath) => {
		const image = imageObjects.get(imagePath);

		if (!image) {
			return full;
		}

		const { index, ...attributes } = image.attributes;

		return Object.entries({
			...attributes,
			src: image.src,
			srcset: image.srcSet.attribute,
			// This attribute is used by the toolbar audit
			...(import.meta.env.DEV ? { 'data-image-component': 'true' } : {}),

View on GitHub (pinned to d081033d5f)

Solutions

  1. Clear the content cache and rebuild: rm -rf .astro then re-run sync/build.
  2. Inspect the imagePath value in the error to see whether it's malformed JSON or a missing import id.
  3. Audit custom remark/rehype plugins that inject images to ensure they emit well-formed metadata.
  4. Verify the referenced image file exists and is importable from the entry's filePath.
Defensive patterns

Strategy: try-catch

Validate before calling

// Validate imagePath is JSON-decodable before render
function isValidImageRef(raw: string) {
  try { const o = JSON.parse(raw.replace(/&(?:#x22|quot);/g,'"').replace(/&(?:#x27|apos);/g,"'")); return o && typeof o.src === 'string'; } catch { return false; }
}

Type guard

const looksLikeImageRef = (s: string) => s.startsWith('{') && s.endsWith('}') && /"src"\s*:/.test(s);

Try / catch

try {
  await updateImageReferencesInBody(html, fileName);
} catch (e) {
  if (e instanceof Error && e.message.startsWith('Failed to parse image reference')) {
    // clear cache and rebuild, or strip malformed image refs from source
  }
  throw e;
}

Prevention

When it happens

Trigger: An HTML attribute matching CONTENT_LAYER_IMAGE_REGEX (__ASTRO_IMAGE_="...") whose value fails to JSON.parse after entity decoding, or whose resolved src/import id cannot be looked up in imageAssetMap, or for which getImage() rejects.

Common situations: A remark/rehype plugin injecting malformed image metadata; image import id present in rendered HTML but missing from the asset map (stale .astro cache); remote image URL that fails getImage validation; manually-injected HTML with the reserved __ASTRO_IMAGE_ attribute; corrupt build cache after partial sync.

Understand the failure class

Related errors


AI-assisted analysis of withastro/astro@d081033d5f (2026-08-12). Data as JSON: /api/errors/ca3e9778c85e0da4. Report an issue: GitHub.