CORS
If your server supposes to handle cross-origin requests, you need to install and configure the CORS Ktor plugin. This plugin allows you to configure allowed hosts, HTTP methods, headers set by the client, and so on.
Install CORS
To install the CORS
plugin, pass it to the install
function in the application initialization code. Depending on the way used to create a server, this can be the embeddedServer
function call ...
... or a specified module.
Configure CORS
CORS-specific configuration settings are exposed by the CORS.Configuration class. Let's see how to configure these settings.
Overview
Suppose you have a server listening on the 8080
port, with the /customer
route responding with JSON data. A code snippet below shows a sample request made using the Fetch API from the client working on another port to make this request cross-origin.
To allow such a request on the backend side, you need to configure the CORS
plugin as follows.
You can find the full example here: cors-backend.
Hosts
To specify the allowed host that can make cross-origin requests, use the host
function. Apart from the hostname, you can specify a port number, a list of subdomains, or the supported HTTP schemes.
To allows cross-origin requests from any host, use the anyHost
function.
HTTP methods
By default, the CORS
plugin allows the GET
, POST
and HEAD
HTTP methods. To add additional methods, use the method
function.
HTTP headers
The CORS
plugin allows the following client headers by default:
Accept
Accept-Language
Content-Language
To allow additional headers, use the header
function.
To allow custom headers, use the allowHeaders
or allowHeadersPrefixed
functions. For instance, the code snippet below shows how to allow headers prefixed with custom-
.
Credentials
By default, browsers don't send credential information (such as cookies or authentication information) with cross-origin requests. To allow passing this information, set the Access-Control-Allow-Credentials
response header to true
using the allowCredentials
property.
Miscellaneous
The CORS
plugin also allows you to specify other CORS-related settings. For example, you can use maxAgeInSeconds
to specify how long the response to the preflight request can be cached without sending another preflight request.
You can learn about other configuration options from CORS.Configuration.