Search code examples
kotlingradlehttpresponsektorresponse-headers

Ktor Response Headers showing null for Set-Cookies


I am making a Gradle KotlinJS App, and I am new to Kotlin. I am using Ktor to ping an API to log in, and from looking at the browser records, I am receiving the return token as a Set-Cookie in the header. "_backend_session=..."

However, when I try to get this SetCookie, using the provided function res.SetCookie(), I get an empty list. I tried various ways of getting it from the headers etc, but the headers seem particularly empty when I log them, and I can't figure out why.

My code:

suspend fun login(username: String, password: String): Pair<HttpStatusCode, Json> {
    val client = HttpClient(Js) {
        install(HttpCookies)
        install(ContentNegotiation) { json(Json) }
    }
    val userData = User(user = UserData(username = username, password = password))

    val response: HttpResponse = client.post("$backend/users/sign_in") {
        headers {
            append(HttpHeaders.AccessControlAllowOrigin, "*")
            append("response_type", "code")
        }
        contentType(ContentType.Application.Json)
        setBody(userData)
    }

    console.log(response.setCookie())

    return Pair(response.status, JSON.parse(response.body()))
}

Solution

  • If you run your code in a browser environment, then the browser blocks frontend Javascript code from accessing the Set-Cookie header:

    From https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie:

    Warning: Browsers block frontend JavaScript code from accessing the Set-Cookie header, as required by the Fetch spec, which defines Set-Cookie as a forbidden response-header name that must be filtered out from any response exposed to frontend code.