ANIMEXD 0 Newbie Poster

i am making api in PHP but i have some problems with cors(preflight) i know how the cors works, my problem is when i request the data from api with (fetch api) i get the response from the server(api) but it suppose to also send cookie for authentication purposes but i can't see any cookies on the browser(chrome) i dont know why?

Here the code for authentication :

<?php

if (isset($_SERVER["HTTP_ORIGIN"]) === true) {
    $origin = $_SERVER["HTTP_ORIGIN"];
    $allowed_origins = array(
        "http://domain"
    );
    if (in_array($origin, $allowed_origins, true) === true) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: POST');
        header('Access-Control-Allow-Headers: Content-Type');
    }
    if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
        exit; // OPTIONS request wants only the policy, we can stop here
    }
}

// include bootstraper
require_once "../../index.php";

// instantiate admin model
$admin_model = new Admin();
$admin_data = $admin_model->read_admin()[0];

// get request raw data from client (user)
$raw_data = json_decode(file_get_contents("php://input"), true);

// success can login
if ($raw_data["username"] == $admin_data["username"]
    && $raw_data["password"] == $admin_data["password"]) {

    // create token
    $new_token = JWT::sign([
        "algo" => "sha256",
        "typ" => "jwt",
    ], [
        "admin" => true,
        "iat" => date("Y-m-d H:i:s"),
        "exp" => date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime(date("Y-m-d H:i:s")))),
    ], SECRET);

    // generate new token
    setcookie("token", $new_token, time() + 60, "/");
    echo json_encode(["message" => "New token generated!", "data" => [], "logged" => true]);
    http_response_code(200);
    exit();

} else { // invalide inputs

    // send error respons
    echo json_encode(["message" => "Error!", "data" => [], "logged" => false]);
    http_response_code(400);
}

Thanks in advance :)

Dani AI

Generated

— short checklist and the two usual fixes when a CORS response returns but the browser does not persist the cookie.

First, the request must include credentials. If you call the API with fetch the client side needs credentials: "include" (cross-origin) so the browser will accept a Set-Cookie from the response. Example:

fetch("https://api.example.com/login", {
  method: "POST",
  credentials: "include",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ username, password })
});

Second, modern browsers block cross-site cookies unless the cookie has the right attributes. For cross-site Set-Cookie you typically need SameSite=None and Secure (and Secure requires HTTPS). On PHP 7.3+ use the options array to set those attributes:

setcookie("token", $token, [
  "expires" => time() + 3600,
  "path" => "/",
  "domain" => ".example.com",
  "secure" => true,
  "httponly" => true,
  "samesite" => "None"
]);

Debug steps: open DevTools > Network and check the actual POST response (not the OPTIONS preflight) for a Set-Cookie header. If it is present but not stored, check SameSite/Secure and the cookie domain/path. Confirm the POST response includes Access-Control-Allow-Credentials: true and an exact Access-Control-Allow-Origin value (not *). Note that document.cookie will not show HttpOnly cookies — look under Application > Cookies or the Response headers to verify storage.

Further reading: MDN on Fetch and on HTTP cookies, and Chrome DevTools docs for inspecting cookies: Using Fetch, HTTP cookies, Chrome DevTools — Cookies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.