Corsica.Router

A router to handle and respond to CORS requests.

This module provides facilities for creating Plug.Router-based routers that handle CORS requests. A generated router will handle a CORS request by:

  • responding to it if it’s a preflight request (refer to Corsica.send_preflight_resp/4 for more information) or
  • adding the right CORS headers to the connection if it’s a valid CORS request.

When a module calls use Corsica.Router, the same options that can be passed to the Corsica router are accepted. Look at the documentation for the Corsica module to find out more.

Examples

defmodule MyApp.CORS do
  use Corsica.Router,
    origins: ["http://foo.com", "http://bar.com"],
    allow_credentials: true,
    max_age: 600,

  resource "/*"

  # We can override single settings as well.
  resource "/public/*", allow_credentials: false
end

Now in your application’s endpoint:

defmodule MyApp.Endpoint do
  plug Plug.Head
  plug MyApp.CORS
  plug MyApp.Router
end

Summary

Defines a CORS-enabled resource

Macros

resource(route, opts \\ [])

Defines a CORS-enabled resource.

This macro takes advantage of the macros defined by Plug.Router (like options/3 and match/3) in order to define regular Plug.Router-like routes that efficiently match on the request url; the bodies of the autogenerated routes just perform a couple of checks before calling either Corsica.put_cors_simple_resp_headers/2 or Corsica.send_preflight_resp/4.

Note that if the request is a CORS preflight request (whether it’s a valid one or not), a response is immediately sent to the client (whether the request is a valid one or not). This behaviour, combined with the definition of an additional OPTIONS route to route, makes Corsica.Router ideal to just put before any router in a plug pipeline, letting it handle preflight requests by itself.

The options given to resource/2 are merged with the default options like it happens with the rest of the functions in the Corsica module.

Examples

resources "/foo", origins: "*"
resources "/wildcards/are/ok/*", max_age: 600