Search code examples
c++cookieshttp-headersesp32

Issue with Setting Multiple Cookies in ESP32 Web Server Response


    void handleLogin(AsyncWebServerRequest *request){
        String sessionId = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        role = "admin";
        
        // Create a JSON response
        DynamicJsonDocument jsonDoc(256);
        jsonDoc["message"] = "welcome";
        jsonDoc["type"] = "success";
        jsonDoc["redirect"] = "/";

        String jsonStr;
        serializeJson(jsonDoc, jsonStr);

        // Create response object and add cookies
        AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonStr);
        String expires = generateExpirationDate(SESSION_TIMEOUT);
        response->addHeader("Set-Cookie", "ESPSESSIONID=" + sessionId + "; Path=/; HttpOnly; Expires=" + expires);
        response->addHeader("Set-Cookie", "UserRole=" + role + "; Path=/; Expires=" + expires);
        request->send(response); // Send response with cookies included
   }

I'm encountering an issue where only the second cookie is being set in the browser, even when I reorder the Set-Cookie headers. The first cookie is consistently ignored. To troubleshoot, I've attempted the following:

  • Removed the HttpOnly attribute.
  • Inspected the network response and the application storage cookies; only the second cookie is applied.
  • Replaced jsonStr with an empty JSON object ({}). Despite these efforts, the issue persists.
  • Tested the web-app in Edge and Chrome browsers.

I'm using ESP32Async/ESPAsyncWebServer v3.6.2


Solution

  • Since the official methods I have seen so far seem inefficient for this part of the project, I used the following method to set two cookies to make the project work:

    String cookieHeader = "ESPSESSIONID=" + sessionId + "; Path=/; Expires=" + expires + "; HttpOnly\r\n"
                      "Set-Cookie: UserRole=" + role + "; Path=/; Expires=" + expires;
    response->addHeader("Set-Cookie", cookieHeader);