Skip to content

Rack Middleware and HMR Dev Mode

Hakan Batuhan Kaba edited this page Nov 13, 2026 · 1 revision

Rack Middleware & HMR Dev Mode

When a Ruby gem ships an embedded Vite, Next.js, or Angular web interface, gem authors need two distinct workflows:

  1. Local Development: Instant Hot Module Replacement (HMR) against a live dev server (localhost:5173, :3000, :4200).
  2. Production Gem Distribution: Fast, secure, zero-Node.js static serving directly out of the installed .gem.

RubyToFaster solves both with zero external dependencies.


1. Mounting RubyToFaster::Middleware

RubyToFaster::Middleware is compatible with both Rack 2.x and Rack 3.x (Rails Engines, Sinatra, Hanami, Roda, Puma, Falcon):

require "rubytofaster"

use RubyToFaster::Middleware,
    root: File.expand_path("../public/vite", __dir__),
    url_prefix: "/studio/assets",
    spa_fallback: true,       # Serves index.html for client-side Angular/React/Vue routes
    index_file: "index.html"

Production Features Built In

  • Zero-CPU .gz Negotiation: Automatically serves pre-compressed <asset>.gz sidecars generated by pkg.precompress_assets when the browser sends Accept-Encoding: gzip, setting Content-Encoding: gzip and Vary: Accept-Encoding.
  • Immutable Fingerprinted Caching: Emits Cache-Control: public, max-age=31536000, immutable for hashed Vite/Angular chunks and /_next/static/* assets.
  • Conditional ETag (304 Not Modified): Eliminates redundant HTML/manifest transfers.
  • Next.js Clean Export Routes: Automatically resolves /docs to docs.html or docs/index.html.
  • Hardened Path Jail: Blocks .., \, NUL bytes, and symlinks with 403 Forbidden, and sets X-Content-Type-Options: nosniff.

2. Live HMR in Development (RTF_DEV_SERVER)

Both RubyToFaster::AssetManifest and the generated Ruby helper (pkg.generate_asset_helper) inspect dev_server: (defaulting to ENV["RTF_DEV_SERVER"]).

Start your Vite dev server during gem UI development:

RTF_DEV_SERVER=http://localhost:5173 bundle exec rackup

In your ERB/Slim/Phlex template, keep the exact same helper call for both development and production:

<%= MyEngine::Assets.html_tags("src/main.ts", framework: :vite, url_prefix: "/studio/assets") %>
  • When RTF_DEV_SERVER is set: Emits <script type="module" src="http://localhost:5173/@vite/client"> + <script type="module" src="http://localhost:5173/src/main.ts">.
  • When packaged in production: Emits fingerprinted <link rel="stylesheet"> and <script type="module"> tags from the embedded manifest.