Symfony icon

Symfony

Put the render call in a controller and your API key never reaches the browser: the browser, and every social crawler, only ever sees a URL on your own domain. Imejis returns the finished image directly in the response, so an action is a single HttpClientInterface request, with nothing to poll and no webhook to receive.

Set two environment variables first:

.env.local
IMEJIS_API_KEY=your_api_key
IMEJIS_DESIGN_ID=your_design_id
IMEJIS_RENDER_URL=https://render.imejis.io

Each one is injected with #[Autowire(env: …)], so the key never appears in an action body, and the routes come from the #[Route] attributes, so there is no routing file to keep in sync.

The fields you override are component.property pairs: headline.text, title.color, image.image. Only what you send changes, and a design's overridable fields are listed in its Share / API panel.

Every block below comes from a real Symfony app that is booted in Docker and called end to end before this page ships.

An endpoint that returns the generated imageAn endpoint that returns the generated image

A route in your app that renders on demand and streams the image straight back, so your render key never reaches the browser. This is the shape to use behind an <img src> on a page you control. ?format= picks png, jpeg, webp or pdf, and the route answers with the content type that matches it. A PDF labelled image/png is a file the browser, the email client and Slack all refuse to open.

src/Controller/OgController.php
<?php
namespace App\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;
 
class OgController extends AbstractController
{
    // The formats the render API accepts. The actions below pass `?format=`
    // through when one is asked for; with none, the render host's default
    // (jpeg) applies.
    private const FORMATS = ['png', 'jpeg', 'webp', 'pdf'];
 
    public function __construct(
        private HttpClientInterface $http,
        // Injecting the env vars keeps them out of the action bodies, and the
        // key out of anything that renders.
        #[Autowire(env: 'IMEJIS_API_KEY')] private string $apiKey,
        #[Autowire(env: 'IMEJIS_DESIGN_ID')] private string $designId,
        #[Autowire(env: 'IMEJIS_RENDER_URL')] private string $base,
        // The variation id of a multi-size design's second canvas — what the
        // /og-size action maps its "story" size to.
        #[Autowire(env: 'IMEJIS_VARIATION_ID')] private string $variationId,
    ) {
    }
 
    // Render on demand and send the image straight back. The key stays on the
    // server, so it never reaches the browser — point an <img src>, or an
    // og:image, at this route.
    //
    // `?format=` decides what comes back — png · jpeg · webp · pdf — and with
    // no format the render host's default (jpeg) applies. Either way the
    // response carries whatever type the render API set, passed straight
    // through: a PDF labelled `image/jpeg` is a file the browser, the email
    // client and Slack all refuse to open.
    #[Route('/og', methods: ['GET'])]
    public function show(Request $request): Response
    {
        $requested = $request->query->get('format', '');
        $query = in_array($requested, self::FORMATS, true) ? ['format' => $requested] : [];
 
        $upstream = $this->http->request('POST', "{$this->base}/v1/{$this->designId}", [
            'headers' => ['dma-api-key' => $this->apiKey],
            'query' => $query,
            'json' => [
                'headline.text' => $request->query->get('title', 'Hello from Symfony'),
                'subtitle.text' => $request->query->get('subtitle', ''),
            ],
        ]);
 
        if (200 !== $upstream->getStatusCode()) {
            return new Response('render failed', 502);
        }
 
        return new Response($upstream->getContent(), 200, [
            'Content-Type' => $upstream->getHeaders(false)['content-type'][0] ?? 'image/jpeg',
            // Renders are deterministic, so cache aggressively at the
            // edge/CDN — and every request to the render API is one metered
            // render.
            'Cache-Control' => 'public, immutable, no-transform, max-age=31536000',
        ]);
    }
}

One endpoint every size and jpeg qualityOne endpoint, every size, and JPEG quality

A multi-size design carries several canvases: an OG image, a square post, a vertical story. ?variation=<id> picks which one the route renders, and omitting it gives the base size, so one endpoint serves every size your pages ask for. ?quality= trades file size for fidelity on JPEG only; png, webp and pdf ignore it.

src/Controller/OgController.php
<?php
namespace App\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;
 
class OgController extends AbstractController
{
    // The formats the render API accepts. The actions below pass `?format=`
    // through when one is asked for; with none, the render host's default
    // (jpeg) applies.
    private const FORMATS = ['png', 'jpeg', 'webp', 'pdf'];
 
    public function __construct(
        private HttpClientInterface $http,
        // Injecting the env vars keeps them out of the action bodies, and the
        // key out of anything that renders.
        #[Autowire(env: 'IMEJIS_API_KEY')] private string $apiKey,
        #[Autowire(env: 'IMEJIS_DESIGN_ID')] private string $designId,
        #[Autowire(env: 'IMEJIS_RENDER_URL')] private string $base,
        // The variation id of a multi-size design's second canvas — what the
        // /og-size action maps its "story" size to.
        #[Autowire(env: 'IMEJIS_VARIATION_ID')] private string $variationId,
    ) {
    }
 
    // One design, several canvases — an OG image, a square post, a vertical
    // story. `?variation=<id>` picks which one you get; with none you get the
    // base size. Map YOUR OWN size names to the ids (the design's Share / API
    // panel lists them) so a page asks for "story", not for an id.
    //
    // `?quality=` trades file size for fidelity on JPEG only — png, webp and
    // pdf ignore it.
    #[Route('/og-size', methods: ['GET'])]
    public function ogSize(Request $request): Response
    {
        // null is the base canvas: a render with no `variation` at all.
        $sizes = ['og' => null, 'story' => $this->variationId];
        $size = $request->query->get('size', 'og');
        if (!array_key_exists($size, $sizes)) {
            return new JsonResponse(['error' => "unknown size: {$size}"], 404);
        }
 
        $query = [];
        if ($sizes[$size]) {
            $query['variation'] = $sizes[$size];
        }
        $requested = $request->query->get('format', '');
        if (in_array($requested, self::FORMATS, true)) {
            $query['format'] = $requested;
        }
        $quality = $request->query->getInt('quality');
        if ($quality >= 1 && $quality <= 100) {
            $query['quality'] = $quality;
        }
 
        $upstream = $this->http->request('POST', "{$this->base}/v1/{$this->designId}", [
            'headers' => ['dma-api-key' => $this->apiKey],
            'query' => $query,
            'json' => ['headline.text' => $request->query->get('title', 'Every size')],
        ]);
 
        if (200 !== $upstream->getStatusCode()) {
            return new Response('render failed', 502);
        }
 
        return new Response($upstream->getContent(), 200, [
            'Content-Type' => $upstream->getHeaders(false)['content-type'][0] ?? 'image/jpeg',
            'Cache-Control' => 'public, immutable, no-transform, max-age=31536000',
        ]);
    }
}

An endpoint that returns a hosted or signed image urlAn endpoint that returns a hosted or signed image URL

Ask for ?delivery=hosted (a public URL) or ?delivery=signed (a private, expiring one) and hand the URL to the caller instead of the bytes, which is what you want for an email, a webhook payload, or a share card.

src/Controller/OgController.php
<?php
namespace App\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;
 
class OgController extends AbstractController
{
    // The formats the render API accepts. The actions below pass `?format=`
    // through when one is asked for; with none, the render host's default
    // (jpeg) applies.
    private const FORMATS = ['png', 'jpeg', 'webp', 'pdf'];
 
    public function __construct(
        private HttpClientInterface $http,
        // Injecting the env vars keeps them out of the action bodies, and the
        // key out of anything that renders.
        #[Autowire(env: 'IMEJIS_API_KEY')] private string $apiKey,
        #[Autowire(env: 'IMEJIS_DESIGN_ID')] private string $designId,
        #[Autowire(env: 'IMEJIS_RENDER_URL')] private string $base,
        // The variation id of a multi-size design's second canvas — what the
        // /og-size action maps its "story" size to.
        #[Autowire(env: 'IMEJIS_VARIATION_ID')] private string $variationId,
    ) {
    }
 
    // Ask for a stored URL instead of bytes. `hosted` is public and
    // permanent; `signed` is private and expires (`expiresIn` is minutes).
    #[Route('/og-url', methods: ['GET'])]
    public function ogUrl(Request $request): JsonResponse
    {
        $delivery = $request->query->get('private') ? 'signed' : 'hosted';
        $query = ['delivery' => $delivery];
        // The stored URL carries the extension of the format it was rendered
        // in, so pass the format through here too — a recipient that sniffs by
        // extension (an email client, a Slack unfurl) needs `.pdf` to say pdf.
        $requested = $request->query->get('format', '');
        if (in_array($requested, self::FORMATS, true)) {
            $query['format'] = $requested;
        }
        if ('signed' === $delivery) {
            $query['expiresIn'] = 30;
        }
 
        // { url, format, file: { size }, expiresAt (signed only) }
        $stored = $this->http->request('POST', "{$this->base}/v1/{$this->designId}", [
            'headers' => ['dma-api-key' => $this->apiKey],
            'query' => $query,
            'json' => ['headline.text' => $request->query->get('title', 'Shared card')],
        ])->toArray(false);
 
        return $this->json([
            'url' => $stored['url'] ?? null,
            'format' => $stored['format'] ?? null,
            'expiresAt' => $stored['expiresAt'] ?? null,
        ]);
    }
}

Bulk image generation from a routeBulk image generation from a route

One POST to /bulk renders many images, a row per record or one per size, and returns a URL for each, in the order you sent them.

src/Controller/OgController.php
<?php
namespace App\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;
 
class OgController extends AbstractController
{
    // The formats the render API accepts. The actions below pass `?format=`
    // through when one is asked for; with none, the render host's default
    // (jpeg) applies.
    private const FORMATS = ['png', 'jpeg', 'webp', 'pdf'];
 
    public function __construct(
        private HttpClientInterface $http,
        // Injecting the env vars keeps them out of the action bodies, and the
        // key out of anything that renders.
        #[Autowire(env: 'IMEJIS_API_KEY')] private string $apiKey,
        #[Autowire(env: 'IMEJIS_DESIGN_ID')] private string $designId,
        #[Autowire(env: 'IMEJIS_RENDER_URL')] private string $base,
        // The variation id of a multi-size design's second canvas — what the
        // /og-size action maps its "story" size to.
        #[Autowire(env: 'IMEJIS_VARIATION_ID')] private string $variationId,
    ) {
    }
 
    // One POST renders many images and returns a URL for each, in the order
    // sent — a row per record, or one per size.
    #[Route('/og-bulk', methods: ['POST'])]
    public function ogBulk(Request $request): JsonResponse
    {
        $rows = $request->toArray()['rows'] ?? [];
 
        $bulk = $this->http->request('POST', "{$this->base}/bulk", [
            'headers' => ['dma-api-key' => $this->apiKey],
            'json' => [
                'designId' => $this->designId,
                'delivery' => 'hosted',
                'format' => 'png',
                'data' => array_map(static fn (array $row) => [
                    'headline.text' => $row['name'],
                    'subtitle.text' => $row['role'] ?? '',
                ], $rows),
            ],
        ])->toArray(false);
 
        return $this->json([
            'summary' => $bulk['summary'],
            'urls' => array_map(static fn (array $r) => $r['url'] ?? null, $bulk['results']),
        ]);
    }
}

Using the image url directly in a templateUsing the image URL directly in a template

For a public design you can skip the proxy entirely and point an <img> at the render URL with the field values in the query string. Keep the proxy when the key must stay private. That is the right default.

templates/og/card.html.twig
{#
  og:image points at YOUR OWN route, so crawlers fetch your domain and get the
  absolute URL they need. In a real template this is where the entity's title
  goes: url('og', {title: post.title}).
#}
<head>
  <meta property="og:image" content="{{ og_image }}">
  <meta name="twitter:card" content="summary_large_image">
</head>
 
{#
  For a PUBLIC design you can skip the proxy and point an <img> straight at the
  render URL — but the key then ships in the markup, so it has to be one you
  are happy to expose. Keep the proxy whenever it must stay private: that is
  the right default, and what the show action above is for.
#}
<img src="{{ direct }}" width="1200" height="630" alt="Card for {{ title }}">

Dynamic OG images. The card action above is the whole link-preview pattern, and getSchemeAndHttpHost() is what makes og:image the absolute URL a crawler needs. In a Twig template you would set it from the entity, as <meta property="og:image" content="{{ url('app_og_show', {title: post.title}) }}">, which is Symfony's default name for that action unless you give the #[Route] one of your own. X, LinkedIn, Slack and iMessage then fetch your domain and get a freshly rendered 1200×630 image for that post.

The response is the raw image (`image/jpeg` by default). Choose the format with `?format=png|jpeg|webp|pdf` (default jpeg) and set JPEG quality with `?quality=1-100`. Store the result and get a URL back with `?delivery=hosted` (or `?delivery=signed&expiresIn=60`), and render a specific size of a multi-size design with `?variation=<id>`.

ParameterValuesDefaultWhat it does
?format=png · jpeg · webp · pdfjpegOutput image format.
?quality=1–100noneCompression quality for lossy output; ignored for other formats. (JPEG only)
?delivery=stream · hosted · signedstreamstream = raw image bytes (default); hosted = store + return a public URL; signed = store + return a time-limited URL.
?expiresIn=minutes60Signed-URL lifetime in minutes (default 60, max 10080 = 7 days). (delivery=signed only)
?variation=<size id>masterWhich multi-dimension SIZE to render. Omit or use "master" for the base size; an unknown id falls back to the master. (multi-size designs only)
  • PNG (?format=png): Lossless, supports transparency. Largest file.
  • JPEG (?format=jpeg): Smaller, lossy, no transparency. Quality adjustable.
  • WebP (?format=webp): Smallest, supports transparency. Modern browsers.
  • PDF (?format=pdf): Vector page, for print and documents.

See the delivery modes and generate images with the API guides.

Laravel has the same five actions with file routing, and the PHP page has the raw calls. The card action renders a Twig template, so the app needs twig-bundle installed; without it the controller boots and that one action fails. getContent() buffers the image, and every request is one render, with 100 free a month on pricing.