0

I'm trying to use setcookie inside a WP REST request, but it isn't working. The REST request runs properly and performs it's other duties well, but it doesn't set any cookies.

Here's my example code, which is running on mywebsite.com

add_action( 'rest_api_init', function () {
    register_rest_route( 'my_auth/v1', '/auth_login', array(
        'methods' => array('POST'),
        'callback' => 'auth_login',
    ));

});


function auth_login( WP_REST_Request $request ) {
    update_post_meta(1234, 'test_field', 'test_value'); // this works!
    setcookie('auth_token', 'test1234', time()+3600, "/", 'mywebsite.com'); // this doesn't work
    return 'test';
}

If I send an AJAX request to my endpoint (mywebsite.com/wp-json/my_auth/v1/auth_login), the update_post_meta call works fine, but the setcookie call does not. I have tested this by visiting mywebsite.com after a request, which has no cookies set.

4
  • Do you see the set-cookie directive in the return headers from the rest call? Commented Jan 6, 2017 at 17:06
  • @GentlemanMax Yes! They are there in the Response Headers: Set-Cookie:auth_token=xxxx-xxxx-xxxx-xxxx-xxxx; expires=Fri, 06-Jan-2017 18:08:37 GMT; Max-Age=3600; path=/; domain=mywebsite.com - but they don't get set. Commented Jan 6, 2017 at 17:10
  • Hmm, is this a cross domain request? If so then you might be running up against a CORS issue. Commented Jan 6, 2017 at 17:14
  • @GentlemanMax yeah, it is cross-domain. I'm building a particularly tricky single sign-on implementation for a client. I've learnt that setting Access-Control-Allow-Credentials: true in my headers may work - giving that a try now. Commented Jan 6, 2017 at 17:16

2 Answers 2

2

Adding this line to my $.ajax call fixed the problem for me.

$.ajax({
    xhrFields: { withCredentials: true },
    // the rest...

Sidenote: this requires the following header to be set on the server-side, which is enabled by default with the REST API (it seems).

Access-Control-Allow-Credentials:true
0

You need to add the following line to your ajax call:

xhrFields: { withCredentials: true }
2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 19, 2022 at 10:35
  • 1
    plus I don't think that adds anything to Rory's answer?
    – Rup
    Commented Jan 19, 2022 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.