Skip to content

Filters ​

Filters are methods that run around an action's call block. Declare them by name:

crystal
class Posts::ShowPost < Blog::BaseAction
  get "/posts/:id"

  before authenticate
  after record_view

  call do
    input = validate(ShowPostContract)
    if post = store.get_post?(id: input.id)
      render_json({id: post.id, title: post.title})
    else
      render_json({error: "post_not_found"}, status_code: 404)
    end
  end

  private def authenticate
    # ...
  end

  private def record_view
    ::Log.info { "post_viewed path=#{request.path}" }
  end
end
before
Authentication, rate limits, read_input. Can halt the request.
call
validate(...)
Your code.
after
Auditing, metrics, headers.
FilterRunsTypical use
beforeBefore callAuthentication, rate limiting, read_input, rejecting requests cheaply
afterAfter call finishesAuditing, metrics, adding headers

Filters run in the order they're declared. They work with the raw request — headers, request.path, request.route_params. Input is validated inside call, so load records there, after validate, rather than in a filter.

Authenticate in a before filter

A before filter runs before a JSON body or a multipart upload is read, so it can reject a request cheaply. Put authentication there — usually once, in Blog::BaseAction.

Halting a request ​

To stop processing, write a response and return byebye:

crystal
private def authenticate
  token = request.headers["Authorization"]?
  unless token == "Bearer #{ENV["API_TOKEN"]}"
    render_json({error: "unauthorized"}, status_code: 401)
    return byebye
  end
end

When a before filter returns byebye, the remaining filters, the call block and every after filter are skipped. When an after filter returns it, the remaining after filters are skipped.

Any other return value — nil, true, a record — means "carry on". You can return continue to make the intent explicit.

Inheritance ​

Filters declared on a base class run for every subclass, before the subclass's own filters:

crystal
abstract class Blog::BaseAction < ::BaseAction
  before authenticate

  private def authenticate
    # ...
  end
end

class Posts::ListPosts < Blog::BaseAction
  get "/posts"
  before check_rate_limit   # runs after authenticate

  # ...
end

A subclass's filters also run when it inherits its call block from a parent action.

Skipping an inherited filter ​

crystal
class Sessions::CreateSession < Blog::BaseAction
  post "/sessions"
  skip authenticate   # logging in can't require being logged in

  # ...
end

skip removes a before or after filter by name for this action and its subclasses. Skipping a filter that isn't declared is a compile error, so a renamed filter can't silently stay active.

Filters and validation errors ​

validate runs inside call. If it fails, Runcobo responds with the errors (422, or 400/413/415 for an unreadable body), the rest of call is skipped, and after filters don't run. Every before filter has already run by then.

Request-wide middleware ​

Filters are per action. For behavior that applies to every request — including unmatched routes and static files — write an HTTP::Handler instead. See Server & Middleware.

Released under the MIT License.