Ruby on Rails icon

Ruby on Rails

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 Net::HTTP call, with nothing to poll and no webhook to receive.

Set two environment variables first (with dotenv-rails, Rails credentials, or your host's config):

.env
IMEJIS_API_KEY=your_api_key
IMEJIS_DESIGN_ID=your_design_id

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 Rails app that is booted with Puma in Docker and called end to end before this page ships.

Route the five actionsRoute the five actions

Rails keeps routing in one file, so this is where the actions below become URLs.

config/routes.rb
Rails.application.routes.draw do
  get "og", to: "og#show"
  get "og-size", to: "og#og_size"
  get "og-url", to: "og#stored_url"
  post "og-bulk", to: "og#og_bulk"
  get "card", to: "og#card"
end

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.

app/controllers/og_controller.rb
require "json"
require "net/http"
 
class OgController < ApplicationController
  BASE = ENV.fetch("IMEJIS_RENDER_URL", "https://render.imejis.io")
  HEADERS = {
    "dma-api-key" => ENV["IMEJIS_API_KEY"],
    "Content-Type" => "application/json"
  }.freeze
 
  # 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.
  FORMATS = %w[png jpeg webp pdf].freeze
 
  # 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 action.
  #
  # `?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.
  def show
    # request.query_parameters, not params: Rails reads params[:format] as the
    # RESPONSE format, so `?format=pdf` would also tell Rails to render a pdf
    # template and raise UnknownFormat before this action could answer.
    requested = request.query_parameters["format"]
    query = FORMATS.include?(requested) ? "?format=#{requested}" : ""
 
    uri = URI("#{BASE}/v1/#{ENV['IMEJIS_DESIGN_ID']}#{query}")
    upstream = Net::HTTP.post(uri, {
      "headline.text" => params[:title] || "Hello from Rails",
      "subtitle.text" => params[:subtitle].to_s
    }.to_json, HEADERS)
    return head :bad_gateway unless upstream.is_a?(Net::HTTPSuccess)
 
    # Renders are deterministic, so cache aggressively at the edge/CDN — and
    # every request to the render API is one metered render.
    headers["Cache-Control"] = "public, immutable, no-transform, max-age=31536000"
    send_data upstream.body,
              type: upstream["content-type"] || "image/jpeg",
              disposition: "inline"
  end
end

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.

app/controllers/og_controller.rb
require "json"
require "net/http"
 
class OgController < ApplicationController
  BASE = ENV.fetch("IMEJIS_RENDER_URL", "https://render.imejis.io")
  HEADERS = {
    "dma-api-key" => ENV["IMEJIS_API_KEY"],
    "Content-Type" => "application/json"
  }.freeze
 
  # 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.
  FORMATS = %w[png jpeg webp pdf].freeze
 
  # 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.
  SIZES = { "og" => nil, "story" => ENV.fetch("IMEJIS_VARIATION_ID", "story") }.freeze
 
  def og_size
    size = params[:size] || "og"
    return head :not_found unless SIZES.key?(size)
 
    query = {}
    query["variation"] = SIZES[size] if SIZES[size]
    # request.query_parameters, not params: Rails reads params[:format] as the
    # RESPONSE format (see #show above).
    requested = request.query_parameters["format"]
    query["format"] = requested if FORMATS.include?(requested)
    quality = request.query_parameters["quality"].to_i
    query["quality"] = quality if quality.between?(1, 100)
 
    uri = URI("#{BASE}/v1/#{ENV['IMEJIS_DESIGN_ID']}")
    uri.query = URI.encode_www_form(query)
    upstream = Net::HTTP.post(uri, {
      "headline.text" => params[:title] || "Every size"
    }.to_json, HEADERS)
    return head :bad_gateway unless upstream.is_a?(Net::HTTPSuccess)
 
    headers["Cache-Control"] = "public, immutable, no-transform, max-age=31536000"
    send_data upstream.body,
              type: upstream["content-type"] || "image/jpeg",
              disposition: "inline"
  end
end

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.

app/controllers/og_controller.rb
require "json"
require "net/http"
 
class OgController < ApplicationController
  BASE = ENV.fetch("IMEJIS_RENDER_URL", "https://render.imejis.io")
  HEADERS = {
    "dma-api-key" => ENV["IMEJIS_API_KEY"],
    "Content-Type" => "application/json"
  }.freeze
 
  # 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.
  FORMATS = %w[png jpeg webp pdf].freeze
 
  # Ask for a stored URL instead of bytes. `hosted` is public and permanent;
  # `signed` is private and expires (`expiresIn` is minutes).
  #
  # Not `og_url`: routing `get "og"` generates an `og_url` helper, and Rails
  # treats a method that shadows a helper as internal rather than as an action
  # — the request 404s with "the action could not be found".
  def stored_url
    delivery = params[: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_parameters["format"]
    query["format"] = requested if FORMATS.include?(requested)
    query["expiresIn"] = 30 if delivery == "signed"
 
    uri = URI("#{BASE}/v1/#{ENV['IMEJIS_DESIGN_ID']}")
    uri.query = URI.encode_www_form(query)
    upstream = Net::HTTP.post(uri, {
      "headline.text" => params[:title] || "Shared card"
    }.to_json, HEADERS)
 
    # { url, format, file: { size }, expiresAt (signed only) }
    stored = JSON.parse(upstream.body)
    render json: {
      url: stored["url"],
      format: stored["format"],
      expiresAt: stored["expiresAt"]
    }
  end
end

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.

app/controllers/og_controller.rb
require "json"
require "net/http"
 
class OgController < ApplicationController
  BASE = ENV.fetch("IMEJIS_RENDER_URL", "https://render.imejis.io")
  HEADERS = {
    "dma-api-key" => ENV["IMEJIS_API_KEY"],
    "Content-Type" => "application/json"
  }.freeze
 
  # 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.
  FORMATS = %w[png jpeg webp pdf].freeze
 
  # One POST renders many images and returns a URL for each, in the order sent
  # — a row per record, or one per size.
  def og_bulk
    rows = params[:rows] || []
    upstream = Net::HTTP.post(URI("#{BASE}/bulk"), {
      "designId" => ENV["IMEJIS_DESIGN_ID"],
      "delivery" => "hosted",
      "format" => "png",
      "data" => rows.map do |row|
        { "headline.text" => row[:name], "subtitle.text" => row[:role].to_s }
      end
    }.to_json, HEADERS)
 
    bulk = JSON.parse(upstream.body)
    render json: {
      summary: bulk["summary"],
      urls: bulk["results"].map { |result| result["url"] }
    }
  end
end

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.

app/views/og/card.html.erb
<%#
  og:image points at YOUR OWN action, so crawlers fetch your domain and get an
  absolute URL they can follow. In a real layout this is where the per-record
  title goes: og_url(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 request.base_url is what makes og:image the absolute URL a crawler needs. In a real view you would set it from the record, with og:image as og_url(title: @post.title), the helper that get "og" generates. 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.

The same calls outside Rails are on the Ruby page. Two Rails-specific traps the Docker run surfaced: read request.query_parameters["format"], because params[:format] is the response format and ?format=pdf would make Rails look for a PDF template, and do not name an action og_url when get "og" already generates that helper. send_data buffers the image, and every action call is one render; 100 a month are free, then pricing.