Middleware and Authentication

Grape is built on Rack and has a powerful middleware stack that you can customize to add functionality like authentication, logging, and performance monitoring.

Using Custom Middleware

You can add any Rack-compatible middleware to your API's stack using the use method.

class MyAPI < Grape::API
  # Add Rack's CORS middleware
  use Rack::Cors do
    allow do
      origins '*'
      resource '*', headers: :any, methods: :get
    end
  end

  get '/public' do
    # ...
  end
end

Creating Grape Middleware

For more complex integrations, you can create custom middleware by subclassing Grape::Middleware::Base. This gives you access to before and after hooks in the request lifecycle.

class ApiLogger < Grape::Middleware::Base
  def before
    # env['api.endpoint'] gives access to the current endpoint
    start_time = Time.now
    env['api.start_time'] = start_time
  end

  def after
    end_time = Time.now
    start_time = env['api.start_time']
    logger.info "API request took #{end_time - start_time} seconds"
    nil # Return nil to avoid modifying the response
  end

  def logger
    API.logger
  end
end

class MyAPI < Grape::API
  use ApiLogger
  # ...
end

Managing the Middleware Stack

Besides use (which adds middleware to the end of the stack), you can use insert, insert_before, and insert_after for more precise control over the middleware order.

# Insert MyMiddleware before Grape's Formatter
insert_before Grape::Middleware::Formatter, MyMiddleware

Authentication

Authentication in Grape is typically handled via middleware. Grape provides built-in support for HTTP Basic authentication.

HTTP Basic Authentication

Use the http_basic helper to protect a namespace or specific endpoints.

class MyAPI < Grape::API
  http_basic(realm: 'My Protected Area') do |username, password|
    # Use a secure comparison method in a real application!
    username == 'admin' && password == 'secret'
  end

  get '/protected' do
    'This is a protected resource.'
  end
end

If authentication fails, Grape automatically returns a 401 Unauthorized response.

Other Authentication Strategies

For more complex authentication schemes like OAuth2, you can use existing Rack middleware gems such as:

These can be integrated using the use method as described above.

Logging

Grape provides a logger method that returns a standard Ruby Logger instance. You can configure a custom logger for your entire API.

class MyAPI < Grape::API
  # Set a custom logger
  logger MyCustomLogger.new

  helpers do
    # Make the logger available inside endpoints
    def logger
      MyAPI.logger
    end
  end

  post '/statuses' do
    logger.info "User created a new status"
    # ...
  end
end
For more advanced request logging, consider using gems like grape_logging.