Astro Image Optimization
Reading through Astro’s documentation on images:
We recommend that local images are kept in
src/when possible so that Astro can transform, optimize, and bundle them. Files in thepublic/directory are always served or copied into the build folder as-is, with no processing.
And specifically for images in Markdown files:
Your local images stored in
src/and remote images will be processed and optimized.
From this, I initially assumed that images must live inside the src/ directory to be optimized. But when defining content collections, you explicitly choose the directory they load from—which raised an interesting question.
Findings
After a bit of code spelunking and experimentation, I found that images referenced in Markdown files are still optimized even when the content directory lives outside of src, as a top-level sibling.
The key detail: Astro’s Markdown image optimization is driven by the content collections system, not by whether files physically reside in src. As long as a Markdown file is part of a defined content collection, Astro will process and optimize any images it references—even if the collection is loaded from a custom, top-level content/ directory.
For example, this structure works just fine:
project/├── src/├── content/│ ├── mypost.md│ └── mypic.png└── astro.config.mjsWhen mypost.md references mypic.png using a relative path or standard Markdown image syntax, Astro will:
- Run the image through its optimization pipeline
- Emit optimized assets into the build output (e.g.
_astroby default) - Rewrite the image references in the generated HTML
The important distinction is that images do need to be in src when you’re importing them directly in .astro or .js/.ts files via ESM imports. But for images referenced from Markdown in content collections, they can live right alongside your content—wherever that collection is configured to load from.
If you want to verify this yourself, run pnpm run build and inspect the dist/ output to see the optimized assets in place.