The Hidden Context: Why wp_get_current_user() Fails in Custom REST Routes
When building custom endpoints for WordPress, a common stumbling block is retrieving the currently authenticated user. It seems intuitive that if a user is logged in via the dashboard or a custom form, they should be accessible globally within the request lifecycle. However, simply calling wp_get_current_user() inside a custom route often returns an object with an ID of 0. Similarly, checking is_user_logged_in() might yield false even when credentials are valid.
The root cause lies in how WordPress initializes its core user context during the REST API request lifecycle. Unlike traditional PHP scripts where execution flows linearly and functions like wp_signon immediately set the global $current_user, the REST API runs in a distinct context. When you register a route using register_rest_route, the server-side environment is not automatically aware of a logged-in session unless specific headers or authentication mechanisms are present.
The Context Problem with wp_get_current_user()
In your first attempt, you registered a GET endpoint intended to return the current user. You expected that because the browser sent cookies indicating an active session, WordPress would pick this up. While WP_REST_Server does handle cookie authentication, wp_get_current_user() relies on the internal $current_user global variable being populated.
In many REST API contexts, especially when using nonces or specific auth headers, this global isn't set by default unless you explicitly authenticate the request first. Even simpler: if your custom route is hit directly without a valid session cookie attached to the request (which often happens in cross-origin scenarios or during initial login attempts), the function returns an empty WP_User object with ID 0.
Your second attempt using is_user_logged_in() suffered from the same issue. Without a properly initialized session context inside that specific callback, WordPress treats the user as anonymous.
Handling Authentication Headers Correctly
Your third approach involved creating a custom POST endpoint for login and attempting to return the user data alongside a nonce. You correctly identified that nonces are required for authenticated requests in the REST API. However, the error you encounteredâ{"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid"}âindicates a mismatch between how the nonce was generated and how it was validated.
In your code:
$nonce = wp_create_nonce("wp_rest");
// ... login logic ...
return array('user' => $user, 'nonce' => $nonce);
The problem is that wp_create_nonce() generates a nonce based on the current user's session and the current timestamp. If you return this nonce as part of the JSON response to a client (e.g., a React or Vue app), the frontend cannot use it directly because nonces are not meant to be static tokens passed in headers like X-WP-Nonce.
The X-WP-Nonce header is strictly for pre-authenticated requests. It tells WordPress, "I am who I say I am, and here is proof via a timestamped hash." You cannot generate this nonce after the login action; you must generate it before sending the request to the protected endpoint.
The Correct Pattern: Cookie-Based Authentication
The most robust way to get the current logged-in user in a custom REST route is to ensure the client sends the appropriate authentication headers. WordPress supports two main methods for this: cookies and bearer tokens.
For standard browser-based login flows, relying on Set-Cookie headers from the server is the standard approach. When a user logs in successfully via your custom endpoint, you must ensure the session cookie (wordpress_logged_in_...) is set. Once that cookie exists and is sent back with subsequent requests, wp_get_current_user() will work as expected because the REST API middleware will process the cookie and populate the global context.
If you need to handle cross-origin requests (CORS) or mobile apps where cookies are less reliable, you should switch to Bearer token authentication. This involves generating a JWT or a simple random string upon login and sending it in an Authorization: Bearer <token> header. WordPress provides built-in support for this via the rest_authorization_header filter, allowing you to map tokens directly to user sessions.
Implementing a Secure Login Endpoint
To fix your specific login implementation, avoid returning the nonce in the response body. Instead, focus on ensuring the session cookie is set and returning standard user data without relying on nonces for the initial handshake.
Here is a refined version of the login route that returns user data securely:
add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'POST',
'callback' => function(WP_REST_Request $request) {
// Extract credentials from the request body
$username = sanitize_user( $request->get_param('user_login') );
$password = $request->get_param('user_password');
// Attempt to sign in the user
$user = wp_signon(array(
'user_login' => $username,
'user_password' => $password,
'remember' => true
), false);
if (is_wp_error($user)) {
return new WP_Error('invalid_credentials', 'Invalid username or password.', array('status' => 401));
}
// At this point, wp_signon has set the session cookie.
// The REST API middleware will now see the user as logged in.
$response = new WP_REST_Response();
$response->set_data(array(
'success' => true,
'user_id' => $user->ID,
'username' => $user->user_login,
// Optional: Add other safe user data here
));
return $response;
},
'permission_callback' => '__return_false', // Allow direct access to login endpoint
));
});
By removing the nonce generation from the response and relying on the session cookie established by wp_signon, your subsequent requests to protected routes (like /custom/profile) will successfully invoke wp_get_current_user() with the correct ID. If you need to protect other endpoints, ensure they use the standard authentication headers (Cookie or Authorization) that match the login method used.