CORS
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.
Add dependencies
To use CORS, you need to include the ktor-server-cors artifact in the build script:
Install CORS
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 CORS...
... inside the
embeddedServerfunction call.... inside the explicitly defined
module, which is an extension function of theApplicationclass.
The CORS plugin can also be installed to specific routes. This might be useful if you need different CORS configurations for different application resources.
Configure CORS
CORS-specific configuration settings are exposed by the CORSConfig 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.
Hosts
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 anyHost function.
HTTP methods
By default, the CORS plugin allows the GET, POST and HEAD HTTP methods. To add additional methods, use the allowMethod function.
Allow headers
By default, the CORS plugin allows the following client headers managed by Access-Control-Allow-Headers:
AcceptAccept-LanguageContent-Language
To allow additional headers, use the allowHeader 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-.
Expose headers
The Access-Control-Expose-Headers header adds the specified headers to the allowlist that JavaScript in browsers can access. To configure such headers, use the exposeHeader function.
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 CORSConfig.