Responsive, signed images in a Symfony blog with UX Image and Imagor

🇬🇧

​Before

In the previous post, MinIO became RustFS and the image proxy became Imagor. This one is about what the blog does with it.

Until last week, an image in a post looked like this in Markdown:

![Coolify UI, project configuration](https://cdn.kocal.fr/image/https://minio.kocal.fr/hugo.alliau.me/posts-assets/coolify-symfony-app/coolify-configuration-general.png?width=1200){:width="1200" height="1009" loading="lazy"}

A full URL to a proxy, wrapping a full URL to the bucket, a ?width= picked by hand, and width/height attributes typed by hand too. One of them was wrong (a 929x348 screenshot declared as 931x911) and nobody noticed for two years.

Changing the CDN meant editing every post. There was one <img>, one size, no srcset.

Full disclosure, same as last time: big thanks to my friend Claude, who did ~95% of the work here (this post included) :D

​The idea

Markdown stores an object key, nothing else:

![Coolify UI, project configuration](posts-assets/coolify-symfony-app/coolify-configuration-general.png){width=1200 height=1009}

The rendering layer decides what URL that key becomes. Today it is Imagor on image.kocal.fr; tomorrow it could be Cloudflare Images or anything else Symfony UX Image has a bridge for, and the posts would not change. The whole configuration is a DSN and a preset:

# config/packages/ux_image.yaml
ux_image:
    provider: '%env(UX_IMAGE_DSN)%'
    formats: ['webp']
    presets:
        post:
            format: webp
            quality: 80
# .env (dev), the real one lives in the hosting environment
UX_IMAGE_DSN=imagor://image.kocal.fr?sign_key=<hex-secret>&signer=sha256&sign_truncate=40

​Rendering: a CommonMark renderer that defers to UX Image

Posts are rendered with league/commonmark, with the AttributesExtension already enabled (that is where {width=1200 height=1009} comes from). A custom renderer is registered for Image nodes, with a higher priority than the default one.

It only handles keys. Anything with a scheme, a leading /, or a ./.. segment goes back to the default renderer, so external images and old-style URLs keep working.

final class ObjectKeyImageRenderer implements NodeRendererInterface
{
    public const int CONTENT_WIDTH = 768;
    public const string PRESET = 'post';

    public function __construct(
        private readonly ImageRendererInterface $imageRenderer,
        private readonly Environment $twig,
    ) {
    }

    public function render(Node $node, ChildNodeRendererInterface $childRenderer): ?string
    {
        $url = $node->getUrl();
        if (! self::isObjectKey($url)) {
            return null; // let the default renderer handle it
        }

        $attributes = $node->data->get('attributes', []);
        $width = $this->positiveInt($attributes['width'] ?? null);
        $height = $this->positiveInt($attributes['height'] ?? null);
        if ($width === null || $height === null) {
            throw MissingImageDimensionsException::forUrl($url);
        }

        $priority = 'high' === ($attributes['fetchpriority'] ?? null);
        unset($attributes['width'], $attributes['height'], $attributes['fetchpriority']);

        $rendered = $this->imageRenderer->render($url, $this->getAltText($node), new RenderOptions(
            width: $width,
            height: $height,
            priority: $priority,
            preset: self::PRESET,
        ));

        $extra = ['sizes' => \sprintf('(min-width: %1$dpx) %1$dpx, 100vw', min($width, self::CONTENT_WIDTH))];

        return ImageMarkup::img($rendered, new ComponentAttributes(
            [...$extra, ...$attributes],
            $this->twig->getRuntime(EscaperRuntime::class),
        ));
    }
}

Three decisions in there:

  • Dimensions are mandatory. Without them UX Image cannot compute a ratio or a srcset ladder, and the page would get layout shifts. So the renderer throws, with a message that shows the expected syntax, instead of rendering something degraded. A validation constraint on the post's content runs the converter and turns that exception into a form error. A missing dimension is caught in the admin, never by a reader.
  • The markup is not built by hand. ImageMarkup::img() and ComponentAttributes are what the <twig:ux:image> component uses: escaping, style, attribute merging all come for free, and title or class written in Markdown end up on the tag.
  • sizes is explicit. The reading column is 768px wide. UX Image's generated sizes assumes a full-width image, so the renderer passes its own: (min-width: 768px) 768px, 100vw, capped by the image's own width.

Images flagged fetchpriority=high are collected during rendering, and the controller emits a Link: <…>; rel=preload; as=image; imagesrcset=…; imagesizes=… header for them, with the same candidates as the <img>. The browser starts fetching the hero image before it has parsed the HTML.

The result, straight from a live page (candidates trimmed):

<img src="https://image.kocal.fr/_f4sntkp…/929x348/filters:quality(80):format(webp)/posts-assets%2Fauto-approve-and-merge.png"
     alt="Pull request for upgrading to GitHub-native Dependabot"
     srcset="https://image.kocal.fr/f2MP75RW…/640x240/filters:quality(80):format(webp)/posts-assets%2Fauto-approve-and-merge.png 640w,
             https://image.kocal.fr/pxVxaBsx…/750x281/filters:quality(80):format(webp)/posts-assets%2Fauto-approve-and-merge.png 750w,
             …
             https://image.kocal.fr/22lbj_6w…/1858x696/filters:quality(80):format(webp)/posts-assets%2Fauto-approve-and-merge.png 1858w"
     sizes="(min-width: 768px) 768px, 100vw"
     loading="eager" fetchpriority="high" width="929" height="348"
     style="object-fit: cover; max-width: 929px; max-height: 348px; aspect-ratio: 929 / 348; width: 100%; height: auto;" />

Every URL is signed with the Imagor secret: nobody can ask Imagor for a 10000px version, or for an image it was not configured to serve. IMAGOR_UNSAFE is off, and unsigned requests get a 403.

​Uploading from the editor

The admin is EasyAdmin with a CodeMirror field for the Markdown. The old "Insert image" button inserted ![]() and left you to find a URL. It now opens a file picker, and the editor also accepts dropped files and pasted screenshots.

Server side, one endpoint: POST /admin/blog/post-images, behind the admin firewall and a stateless CSRF token, which receives file, slug and _token. It validates the file by sniffing its real MIME type (PNG, JPEG, GIF, WebP, AVIF; SVG is refused because getimagesize() cannot read it and the renderer needs dimensions), writes it to the bucket through Flysystem under posts-assets/<slug>/<slugified-name>.<ext> (with a -2, -3 suffix on collision, never an overwrite: Imagor and Cloudflare caches are not invalidated), and answers:

{"key": "posts-assets/my-post/my-shot.png", "width": 1200, "height": 630}

Client side, the Stimulus controller stays thin: three small modules do the work and each has its Vitest test. The controller inserts a placeholder at the cursor right away, uploads, then replaces the placeholder with the final snippet (or removes it and shows the error):

// assets/markdown/image_snippet.js
export function imageSnippet({ alt, key, width, height }) {
    const attributes = width && height ? `{width=${width} height=${height}}` : "";

    return `![${alt}](${key})${attributes}`;
}

export function uploadingPlaceholder(name) {
    return `![Uploading ${name}…]()`;
}
// assets/controllers/markdown_editor_controller.js (excerpt)
async #uploadAndReplace(file, placeholder, slug) {
    try {
        const result = await uploadImage(file, { url: this.uploadUrlValue, slug, csrfToken: this.csrfTokenValue });
        this.#replacePlaceholder(placeholder, imageSnippet({ alt: altFromFilename(file.name), ...result }));
        this.#clearError();
    } catch (error) {
        this.#replacePlaceholder(placeholder, "");
        this.#showError(error.message);
    }
}

One gotcha: when the CSRF check fails, Symfony's firewall answers with a redirect to the login page, which fetch() follows. So the upload module treats any 200 that is not JSON with a key as a failure, and does not trust the status code.

​Migrating fifteen posts

Fifteen posts, twelve legacy image URLs. A console command, app:blog:rewrite-image-urls --dry-run, rewrites each legacy URL to its key, fetches the real dimensions from the bucket, prints what it would write, and refuses to save a post whose rewritten content does not render.

The dry run earned its keep. The unit tests used {width=1200 height=630}, but the real posts used kramdown-style {:width="1200" height="1009" loading="lazy"}, with a leading colon and quotes. The first version of the rewriter did not recognise those as dimensions and would have appended a second pair next to them.

The fix: always probe the object, keep the author's width as a display width (capped at the real width), and recompute the height from the real ratio, replacing whatever was there. That is also how the 931x911 lie became 929x348.

$width = max(1, min($authoredWidth ?? $real->width, $real->width));
$height = max(1, (int) round($width * $real->height / $real->width));

Then the real run, a database dump beforehand, and a Cloudflare purge afterwards.

​What it changed

  • Posts reference images by key. The CDN is a DSN.
  • Every image is WebP, served in up to nine widths, with width/height and aspect-ratio set, so no layout shift.
  • Hero images are preloaded with imagesrcset.
  • URLs are signed; the bucket is private.
  • Adding an image to a post is a drag and drop.

Old cdn.kocal.fr URLs are not redirected: Imagor URLs are signed, Caddy cannot forge them, and the only consumers of those URLs were my own pages, which now render the new ones. If someone hot-linked a screenshot of mine, I am sorry, and also a little flattered.

​One last thing

I hope these two posts made you want to try Symfony UX Image. It is young and still marked experimental, but it already speaks to Cloudflare Images, Cloudinary, Imagor, Imgix, IPX and KeyCDN, and the whole point is that your templates and your content do not care which one. Try it on a single <img>, and tell us what is missing: issues and pull requests are welcome on symfony/ux.