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?
answer
- one middleware stack per app
- api_only is app-wide
- resources lose new and edit
- generators stop writing views
- per-controller ActionController::API base
basics
~20 sKeep 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.
solid answer
~40 s`config.api_only` is an application setting, not a controller setting. Setting it to true removes `ActionDispatch::Cookies`, the session store, `ActionDispatch::Flash`, the CSP and permissions-policy middleware, `Rack::MethodOverride` and `Rack::TempfileReaper` from the one middleware stack every request shares. It also makes `resources` skip `new` and `edit`, makes generators skip views and helpers, and defaults development error responses to the `:api` format. A hybrid app needs all of that for its Hotwire pages, so it keeps the flag false and makes the API lean at the controller level instead: an `Api::BaseController < ActionController::API` for the JSON namespace, `ActionController::Base` for the rest. The browser middleware still runs on API requests, which costs little, but it means API controllers must not quietly rely on the session cookie without forgery protection.
code
ruby · 10 lines# config/routes.rb
Rails.application.routes.draw do
resources :workouts # HTML, includes new and edit
namespace :api do
namespace :v1 do
resources :workouts, except: %i[new edit]
end
end
endgo deeper
Know that config.api_only is an app-wide switch, while ActionController::API is a superclass chosen controller by controller.
List what api_only changes beyond middleware: routes without new and edit, generators, and the debug error format.
Design the two-base-controller layout and close the gap where API controllers could be authenticated by the HTML session cookie without CSRF protection.
Decide when the API deserves its own deployable versus sharing one Rails app with the Hotwire front end.
## Two levers, two scopes Rails gives you two separate ways to slim down for JSON: - **`config.api_only = true`** in `config/application.rb` changes the **application**: what the default middleware stack contains, what generators write, and how routes and error pages behave. - **`ActionController::API`** as a superclass changes **one controller hierarchy**: which feature modules its actions include. A new API-only app uses both. An app that also serves HTML can only use the second. ## Everything api_only changes | Area | With `config.api_only = true` | |---|---| | Middleware | no `ActionDispatch::Cookies`, session store, `ActionDispatch::Flash`, CSP or permissions-policy middleware, `Rack::MethodOverride`, `Rack::TempfileReaper` | | Routes | `resources` generates five actions, without `new` and `edit`; singular `resource` loses them too | | Generators | views, helpers and assets are skipped; scaffold controllers render JSON | | Errors | `config.debug_exception_response_format` defaults to `:api` | Every one of those breaks a Hotwire front end. Without cookies and the session store, the authentication generator's sign-in cannot persist; without flash, redirects lose their notices; without the CSP middleware, any policy you configured is no longer sent; without `MethodOverride`, an HTML form that relies on the hidden `_method` field can no longer reach a PATCH or DELETE route; without `new` and `edit` routes, the HTML forms have nowhere to live. ## The hybrid layout 1. Leave `config.api_only` unset (false). 2. Keep `ApplicationController < ActionController::Base` for the HTML side. 3. Add a separate base for the API namespace: ```ruby # app/controllers/api/base_controller.rb class Api::BaseController < ActionController::API include ActionController::HttpAuthentication::Token::ControllerMethods before_action :authenticate_device private def authenticate_device authenticate_or_request_with_http_token { |token, _options| Device.find_by(token:) } end end ``` 4. Make every `Api::V1::*Controller` inherit `Api::BaseController`. 5. Restrict API routes explicitly, for example `resources :workouts, only: %i[index show create update destroy]`, since the routing default still includes `new` and `edit`. 6. When generating API resources, pass `--api` to the scaffold generator or write controllers by hand, because the app-wide generators still produce views. ## What still runs on API requests Because the stack is shared, an API request still passes through the cookies, session and flash middleware. The cost is small, since the session loads lazily only when touched. The risk is semantic: - A browser that is signed in to the HTML side sends its session cookie to `/api/...` too. If an API controller reads `session[:user_id]` to authenticate, it is cookie-authenticated, and `ActionController::API` carries no forgery protection. Either authenticate the API only with tokens, or include forgery protection for that path. - If the app configures a Content Security Policy, its header is added to JSON responses as well, which is harmless. ## When a separate API app is the better answer Splitting into two deployables is worth it only when the API has its own scaling profile, team or release cadence. Most apps with a Hotwire UI and a mobile API are better served by one codebase, shared models and the two-base-controller layout above, deployed as one unit. ## Checking what you have - `bin/rails middleware` lists the stack, so you can confirm cookies and sessions are present. - `bin/rails routes -g workouts` shows whether `new` and `edit` exist. - `Api::BaseController.ancestors` shows exactly which modules the API side includes. ## Testing the boundary A hybrid app is worth one or two tests that pin the split down: 1. A request test that `GET`s an API endpoint with a signed-in browser session but no token and expects `401`, proving the API does not fall back to the cookie. 2. A request test that submits an HTML form to a PATCH route and expects the update, proving `Rack::MethodOverride` and the session are still in the stack. 3. An assertion that `Api::BaseController.ancestors` does not include `ActionController::RequestForgeryProtection`, so nobody switches the base class back to `ActionController::Base` without noticing what changes. These guard against the most common regression: someone sets `config.api_only = true` to "speed up the API" and logs out every HTML user.
- What breaks first if you flip config.api_only to true in an app that has Hotwire pages?Sign-in, because `ActionDispatch::Cookies` and the session store leave the stack: writing `session` raises `ActionDispatch::Request::Session::DisabledSessionError`. Flash notices and the CSP header disappear, HTML forms that use the hidden `_method` field lose `Rack::MethodOverride`, and `resources` stops generating `new` and `edit`, so form pages 404.
- How do you generate an API controller inside a hybrid app without getting views?Pass `--api` to the `scaffold` or `scaffold_controller` generator, which then writes the JSON controller template and skips the view templates, or write the controller by hand. The app-wide generator settings still assume HTML because `config.api_only` is false.
- config.api_only can be set per controller or per namespace.
- Setting api_only only affects new code generation, not running requests.
- Subclassing ActionController::API also removes the session middleware for those routes.
- A hybrid app should set api_only and include HTML modules back into Base.
- API controllers in a hybrid app never see the browser's session cookie.