skip to content

Trimmed Middleware & CORS

rails new --api swaps in ActionController::API and drops cookies, sessions, flash and views from the stack. Interviewers ask what is missing, how to add it back, and where rack-cors fits.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In Rails 8.1, what does generating an app with rails new --api change compared with a default rails new app?

level: juniorimportance: must knowfreq 60%

answer

  1. a smaller controller superclass
  2. one flag in config/application.rb
  3. implies two skip flags
  4. two gems left commented out
  5. cors.rb written fully commented

basics

~10 s

rails new --api makes ApplicationController inherit ActionController::API, sets config.api_only = true to trim browser middleware and generators, and skips the asset pipeline and JavaScript; jbuilder and rack-cors arrive commented out.

solid answer

~40 s

Three things change. `ApplicationController` inherits `ActionController::API` instead of `ActionController::Base`, so layouts, helpers, cookies, flash and forgery protection are gone from controllers. `config/application.rb` gets `config.api_only = true`, which builds a smaller middleware stack (no cookies, session, flash or CSP middleware) and makes generators skip views, helpers and assets. And `--api` implies `--skip-asset-pipeline` and `--skip-javascript`, so there is no Propshaft, import map, Turbo or Stimulus. In Rails 8.1 the Gemfile carries `jbuilder` and `rack-cors` only as commented lines, `config/initializers/cors.rb` is written fully commented, and web-console, Capybara and the HTML error pages are left out. Active Record, Action Mailer, the Solid trio and Kamal stay.

code

bash · 3 lines
bash
rails new tracker_api --api --database=postgresql
cd tracker_api
bin/rails middleware

go deeper

for a junior

Recall the three effects: the ActionController::API superclass, config.api_only = true, and no asset pipeline or JavaScript. Mention that rack-cors and jbuilder come commented out.

for a middle

Explain what config.api_only touches at boot: the middleware list, generator output, resources' new and edit routes, and the debug exception format.

for a senior

Show you know what stays (Active Record, mailers, the Solid trio, Kamal) and how to re-enable a dropped piece deliberately rather than flipping the whole app back to Base.

for a principal

Weigh a separate API-only app against API controllers inside a full-stack app: deploy units, shared models, and which clients really need cookies or HTML.

## What the flag is for `rails new tracker_api --api` generates a Rails application whose only job is to answer HTTP requests with data, usually JSON, for clients that render their own UI: a native mobile app, a single-page app on another origin, or another service. Nothing about the domain layer changes. You still get **Active Record**, migrations, Active Job, Action Mailer, Active Storage and the rest. What `--api` removes is the machinery a server-rendered HTML app needs: templates and layouts, cookies and sessions, flash messages, browser-only security headers, and the asset pipeline. The flag works at three levels at once: the controller superclass, the application config, and the generator's own file list. ## The controller superclass The generated `app/controllers/application_controller.rb` is: ```ruby class ApplicationController < ActionController::API end ``` A default app writes `ActionController::Base` there instead and adds `allow_browser versions: :modern` (plus `stale_when_importmap_changes` when import maps are used). **`ActionController::API`** is a slimmer subclass of `ActionController::Metal` that includes only the modules an API needs: rendering with `render json:`, redirects, `before_action` callbacks, `rescue_from`, strong parameters, conditional GET, `rate_limit` and data streaming. Layouts, helpers, `respond_to`, `cookies`, `flash`, `protect_from_forgery` and the HTTP authentication helpers are not included, though each can be included back. ## config.api_only and the trimmed stack `config/application.rb` gains one line: ```ruby config.api_only = true ``` That setting is read in several places when the app boots: - **Middleware.** The default stack skips `Rack::MethodOverride`, `ActionDispatch::Cookies`, the session store, `ActionDispatch::Flash`, the Content Security Policy and Permissions Policy middleware, and `Rack::TempfileReaper`. - **Generators.** `bin/rails generate scaffold` and friends stop writing views, helpers and assets; the scaffold controller renders JSON instead. - **Routes.** `resources` skips the `new` and `edit` routes, since those exist only to serve HTML forms. - **Error pages.** `config.debug_exception_response_format` defaults to `:api`, so development errors come back in the request's format rather than as an HTML debug page. ## What the generator leaves out | Area | Default `rails new` | `rails new --api` | |---|---|---| | Assets and JS | Propshaft, import maps, Turbo, Stimulus | none (`--skip-asset-pipeline`, `--skip-javascript`) | | `jbuilder` gem | active line | commented-out line | | `rack-cors` gem | absent | commented-out line | | `config/initializers/cors.rb` | not written | written, every line commented | | CSP initializer | written | removed | | `app/helpers`, layout, PWA views | written | removed | | `public/400.html` ... `500.html`, icons | written | removed | | web-console, Capybara, Selenium | in the Gemfile | left out | Mailer layouts under `app/views/layouts/` survive unless you also pass `--skip-action-mailer`, because mail still needs templates. ## What stays exactly as in a full app 1. Active Record with your chosen database, `db/` and migrations. 2. The Solid trio (Solid Queue, Solid Cache, Solid Cable) with their config files. 3. Kamal, Thruster, the Dockerfile, Brakeman, RuboCop and `bin/ci` configuration. 4. Action Mailer, Active Storage and Action Cable, unless you skip them separately. ## Turning pieces back on None of this is permanent. Uncommenting `gem "rack-cors"` and the block in `cors.rb` enables CORS; uncommenting `jbuilder` brings JSON templates; including a module such as `ActionController::MimeResponds` in `ApplicationController` restores `respond_to`; and adding `ActionDispatch::Cookies` plus a session store to `config.middleware` restores sessions. An existing full app can go the other way by setting `config.api_only = true` and switching `ApplicationController` to `ActionController::API`. ## Checking what you got Three commands show the difference without reading every generated file: - `bin/rails middleware` prints the stack. In an API app you will not see `ActionDispatch::Cookies`, `ActionDispatch::Session::CookieStore`, `ActionDispatch::Flash` or `Rack::MethodOverride`. - `bin/rails routes` after `bin/rails generate scaffold Workout distance_km:decimal` shows five actions per resource instead of seven, because `new` and `edit` are gone. - `ApplicationController.ancestors` in `bin/rails console` lists `ActionController::API` and its modules, with no `ActionController::Flash` or `ActionController::RequestForgeryProtection` among them. ## Common misreadings - **"API mode removes the database."** It does not; `--api` and `--skip-active-record` are separate flags. - **"CORS is configured for me."** The file exists, but every line is a comment and the gem is not installed. - **"jbuilder is gone."** It is one uncommented line away; Rails leaves it commented because many API apps render with `render json:` alone.

  • How do you turn an existing full-stack Rails app into an API-only one?
    Set `config.api_only = true` in `config/application.rb` and change `ApplicationController` to inherit `ActionController::API`. The middleware stack and generators follow the flag, and `config.debug_exception_response_format` defaults to `:api` unless you set it. Then delete the views, helpers and assets you no longer serve, and check `bin/rails routes` because `resources` stops generating `new` and `edit`.
  • Does --api also skip Action Mailer, Active Storage or the Solid gems?
    No. In Rails 8.1 `--api` implies only `--skip-asset-pipeline` and `--skip-javascript`, which in turn skips Hotwire. Mailers with their layouts, Active Storage, Action Cable, Solid Queue, Solid Cache, Solid Cable, Kamal and Thruster are all generated as usual; skip each with its own flag if you do not want it.

  • --api drops Active Record, so models need a separate ORM gem.
  • rack-cors is installed and allows every origin out of the box.
  • An --api app still gets Propshaft and import maps, just unused.
  • ApplicationController in an --api app inherits ActionController::Metal.
  • config.api_only only changes generators, never the middleware stack.

Assumes Rails 8.1.4's app generator; the commented jbuilder and rack-cors lines, the removed CSP initializer and the skipped HTML error pages are what that version writes for --api.

open as a page

In a Rails API app, how do you configure rack-cors in config/initializers/cors.rb for a single-page app served from another origin?

level: middleimportance: must knowfreq 55%

basics

~20 s

Uncomment gem "rack-cors" and the block in config/initializers/cors.rb, then insert Rack::Cors at position 0 with an allow block naming the SPA's exact origin and a resource listing the paths, methods and request headers it may use.

open as a page

In Rails 8.1, which ActionController::Base features does ActionController::API leave out, and how do you add one back?

level: middleimportance: should knowfreq 45%

basics

~10 s

ActionController::API drops layouts, helpers, respond_to, cookies, flash, forgery protection and the HTTP authentication helpers, and an action without render answers 204. Add a feature back by including its module, such as ActionController::MimeResponds, in ApplicationController.

open as a page

In a Rails 8.1 api_only app, how do you add cookie-based sessions back, and why does the order of the config lines matter?

level: middleimportance: should knowfreq 30%

basics

~10 s

An api_only app has no ActionDispatch::Cookies or session store, so writing session raises DisabledSessionError. In config/application.rb set config.session_store, then use ActionDispatch::Cookies and config.session_store with config.session_options, in that order.

open as a page

In a Rails API that serves a mobile app, how do you lay out Api::V1 and add V2 without breaking clients still on old app versions?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Nest namespace :api and namespace :v1 in config/routes.rb so controllers live in app/controllers/api/v1 as Api::V1::*. Add V2 as a sibling namespace with its own controllers and JSON views, and retire V1 only when old app builds stop calling it.

open as a page

A Rails 8.1 app serves Hotwire pages and a JSON API; should it set config.api_only or only subclass ActionController::API, and why?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Keep config.api_only false and give the API controllers an ActionController::API base. The flag is app-wide: it strips cookies, sessions, flash and CSP middleware, drops new and edit routes and stops view generation, which breaks the HTML side.

open as a page