Ruby on Rails Interview Questions and Answers — Middleware — Part 2

7 min readFeb 11, 2024


  • What is the role of the use method in configuring middleware in Rails?
  • How do you use built-in middleware like Rack::Auth or Rack::Cors in Rails?
  • What is the difference between middleware and filters in Rails controllers?
  • How can you modify the request or response using middleware in Rails?
  • What is the purpose of the env variable in the Rack environment?

6. What is the role of the use method in configuring middleware in Rails?

Let’s say we want to add a custom middleware called CustomLogger to our Rails application to log each request made to the server. First, we need to create the middleware itself. Here's an example of what the CustomLogger middleware might look like:

This middleware logs each incoming request along with its HTTP method and URI.

Next, we need to add this middleware to our Rails application’s middleware stack using the use method. We can do this in the config/application.rb file. Here's how we would modify the file to include our CustomLogger middleware:

With this setup, every incoming request to our Rails application will be logged by the CustomLogger middleware.

It’s important to note that the order in which middleware is added using the use method matters. In this example, we've added our custom middleware at the top of the middleware stack, which means it will be executed before any other middleware. We could adjust the order if we wanted our logging to occur after other middleware. For instance, if we wanted to log in after the Rack::Cors middleware, we could place our config.middleware.use CustomLogger line after config.middleware.use Rack::Cors.

7. How do you use built-in middleware like Rack::Auth or Rack::Cors in Rails?

Rack::Auth (HTTP Basic Authentication)

Rack::Auth provides HTTP Basic Authentication for your Rails application. To use it, you can configure it in your config/application.rb or in specific environment files like config/environments/production.rb if you only want it in certain environments.

In the above configuration:

  • Rack::Auth::Basic middleware is added to the middleware stack.
  • The block passed to Rack::Auth::Basic defines the logic to authenticate users. In this example, it's a basic check where the username must be 'admin' and the password must be 'password'. In a real application, you'd likely perform more secure and sophisticated authentication.

Rack::Cors (Cross-Origin Resource Sharing)

Rack::Cors provides support for Cross-Origin Resource Sharing (CORS) in your Rails application.

In this configuration:

  • Rack::Cors middleware is added to the middleware stack.
  • The allow block defines the CORS policy. In this example, requests from any origin are allowed (origins '*'). You can customize this according to your needs.
  • The resource method specifies the resources (or routes) to which the CORS policy applies, along with the allowed HTTP methods and headers.

Remember to adjust the CORS configuration to fit your application’s security requirements. Allow only the origins, methods, and headers that your application truly needs for security reasons.

8. What is the difference between middleware and filters in Rails controllers?


  • Middleware in Rails intercepts HTTP requests and responses as they flow through the application stack. It sits between the web server and the Rails application, providing a layer of processing that can modify both incoming requests and outgoing responses.
  • Middleware is applied globally to all requests and responses, affecting the entire application. It can perform tasks such as logging, authentication, session management, CORS handling, and more.
  • Middleware operates at a lower level than controllers, handling requests before they are routed to specific controller actions. It is defined and configured at the application level, typically in the config/application.rb file or in environment-specific configuration files.
  • Middleware is executed for every request, regardless of the controller or action being accessed.


  • Filters, on the other hand, are specific to controllers in Rails and are used to execute code before, after, or around controller actions.
  • Filters allow developers to encapsulate common pre-processing or post-processing logic that needs to be executed for multiple actions within a controller or across multiple controllers.
  • Filters are defined within controller classes using before_action, after_action, or around_action declarations. They are scoped to specific controller actions or applied globally to all actions within a controller.
  • Filters provide a way to encapsulate cross-cutting concerns within controller logic, such as authentication, authorization, parameter sanitization, caching, and more.
  • Unlike middleware, filters operate within the context of controller actions, allowing access to controller instance variables, session data, and other controller-specific features.

9. How can you modify the request or response using middleware in Rails?

middleware allows you to intercept and modify both incoming requests and outgoing responses as they pass through the application stack. You can modify the request or response within middleware by accessing and manipulating the environment hash (env) for requests and the response object for responses.

Modifying Requests

Accessing Request Data: Middleware can access request data through the env hash. Common request attributes you might access include REQUEST_METHOD, REQUEST_URI, QUERY_STRING, HTTP_HEADERS, and rack.input (for request body).

Modifying Request Headers or Parameters: You can modify request headers or parameters by directly manipulating the env hash. For example, you can add, remove, or modify headers or parameters as needed.

Modifying Request Body: If the middleware needs to modify the request body, it can read and manipulate the rack.input stream in the env hash. Be cautious when modifying the request body to ensure compatibility with subsequent middleware or the controller action.

Modifying Responses

Accessing Response Object: Middleware can access the response object, typically named response, to modify the response. The response object provides methods to set headers, status code, and response body.

Modifying Response Headers: You can modify response headers by calling methods provided by the response object, such as set_header, delete_header, or header.

Modifying Response Body: Middleware can modify the response body by replacing it entirely or by injecting content. You can access and manipulate the response body through methods like write, <<, or close on the response object.

Here’s a simplified example of middleware that modifies the response headers:

Then, you can include this middleware in your Rails application’s middleware stack, typically in config/application.rb:

This middleware adds a custom header X-Custom-Header to every response. You can modify the middleware logic according to your specific requirements to manipulate requests or responses in different ways.

10. What is the purpose of the env variable in the Rack environment?

The env variable typically includes various key-value pairs representing different aspects of the request, such as:

Request Metadata: Information about the HTTP request itself, including the HTTP method (REQUEST_METHOD), the requested path (PATH_INFO), query parameters (QUERY_STRING), and the protocol (SERVER_PROTOCOL).

Request Headers: Headers sent with the HTTP request, such as HTTP_USER_AGENT, HTTP_ACCEPT, HTTP_HOST, etc.

Request Body: The request body, if applicable, is available through the rack.input key in the env hash. Middleware and applications can read from this input stream to access request data.

Server Information: Information about the server environment, including the server software (SERVER_SOFTWARE), the server's hostname (SERVER_NAME), and the server's port (SERVER_PORT).

Other Environment Variables: Additional environment variables that may be set by the server or middleware components.

The env variable serves as the primary means for Rack middleware and applications to access and manipulate incoming requests. Middleware can inspect and modify the env hash to perform various tasks such as authentication, logging, request routing, and request/response transformation.

The env variable is a crucial component of the Rack framework, providing a standardized way for web servers and web applications to communicate and process HTTP requests in a flexible and extensible manner.

I appreciate you taking the time to read this. Please follow me on Medium and subscribe to receive access to exclusive content to keep in touch and continue the discussion. Happy Reading..!




Consultant | Freelancer | Ruby on Rails | ReactJS