If your server is supposed 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.
CORS, you need to include the
ktor-server-cors artifact in the build script:
To install the
CORS plugin to the application, pass it to the
install function in the specified module. The code snippets below show how to install
... inside the
... inside the explicitly defined
module, which is an extension function of the
CORS plugin can also be installed to specific routes. This might be useful if you need different
CORS configurations for different application resources.
CORS-specific configuration settings are exposed by the CORSConfig class. Let's see how to configure these settings.
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.
To specify the allowed host that can make cross-origin requests, use the
allowHost function. Apart from the hostname, you can specify a port number, a list of subdomains, or the supported HTTP schemes.
To allow cross-origin requests from any host, use the
By default, the
CORS plugin allows the
HEAD HTTP methods. To add additional methods, use the
By default, the
CORS plugin allows the following client headers managed by
To allow additional headers, use the
To allow custom headers, use the
allowHeadersPrefixed functions. For instance, the code snippet below shows how to allow headers prefixed with
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
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 CORSConfig.