Proxying rails (or any really) server with middleman

While it seems middleman is a great setup for serving a static javascript app front-end for a json API. Using it for that has been a right pain. Looking at the existing solutions on github issues, having the middleman rack & rails rack apps in the same process seems a recipe for much pain.

Using CORS is also a pain (strange errors in the browser, flakiness, probably due to me not giving a F*ck to read up about it enough), which led me to explore setting up middleman as a proxy for, say, any calls to /api. FTW!

Checkout the gist and edit your config & Gemfile. copy the rails_proxy.rb into lib (or just append it to config.rb if you want).

A couple of things:

The Gemfile links to my fork of the rack-proxy repo. This is because rack-proxy causes rack errors because of the way NET:HTTP returns header & body infos. I have one patch pending to fix this, but for the moment, use my repo.

in rails-proxy.rb I am monkey patching Rack::Lint to become a noop. remove this if you dont Linting. Generally if Linting catches something, that something will blow up rack down the line anyway.

I may make a middleman plugin for this in the future, but for now this is pretty simple.

Just a heads up for the community, hopefully it will save you some pain debugging stupid CORS issues.

Cheers

Why not set up your HTTP server process to serve requests to / with the static files generated by Middleman, and /app with your Rack app, rather than doing it in Ruby? That way, you get all the advantages of serving a static site.

How you do this depends on your HTTP server, but if you’re using Nginx, you’d set up a server block with a root pointing to your Middleman output, and a location /app block inside that pointing to your Rack app. Basically, the same way you’d set up static files for any web app, but backwards. (Note: I haven’t actually tested this, let me know if I’ve made a mistake here.)

1 Like

This is mainly meant for development, once you hit production, the assets will be static & served as such…