I am trying to set a cookie from an API server on a subdomain api.talopakettiin.fi
and access it on the main domain talopakettiin.fi
within the same broader domain. I’m using Express.js on the server and wordpress php on the client-side to handle the requests and cookies. I find the cookie in the cookies tab but it is under the subdomain like so:
and I set the cookie in the response after signing in:
res.cookie("Token", jwtToken, {
domain: ".talopakettiin.fi",
secure: true,
httpOnly: true,
path: "/",
sameSite: "None",
});
But when i try to access it in my client's functions.php file
function handle_button_click() {
error_log('Button clicked!'); // Example log for testing
$api_url = 'https://api.talopakettiin.fi/forms/receive-form-data';
$jwt_token = isset($_COOKIE['Token']) ? $_COOKIE['Token'] : 'Token not found';
error_log("Extracted Token: " . $jwt_token);
$response = wp_remote_post($api_url, [
'method' => 'POST',
'body' => "So much data",
'headers' => [
'Content-Type' => 'application/json',
$jwt_token
],
]);
wp_send_json_success(array('message' => 'Button was clicked!'));
}
add_action('wp_ajax_handle_button_click', 'handle_button_click'); // For logged-in users
then $jwtToken is always 'Token not found'. How can i fix this issue?
Okay so I fixed the issue and realized where it stems from. In Express the "domain" attribute will get filtered because for some reason express doesn't like sending it. So to ensure it does get sent, you have to:
app.use('trust proxy', true)
and 2) In your index.js file set
app.use((req, res, next) => {
req.domain = req.headers.host;
next();
});
This way the cookie's domain attribute gets set to the intended URL.