Limit REST API CORS to Your Own Apps
Replaces WordPress's permissive cross-origin (CORS) headers with an allow-list, so only the browser apps you name, such as a headless front end, can call the REST API with credentials.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
// Origins allowed to call the REST API from a browser.
$allowed = array( 'https://app.example.com' );
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function ( $served ) use ( $allowed ) {
$origin = get_http_origin();
if ( $origin && in_array( $origin, $allowed, true ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Headers: Authorization, Content-Type, X-WP-Nonce' );
}
header( 'Vary: Origin', false );
return $served;
} );
}, 15 );
Notes
List exact origins including the protocol and no trailing slash. Requests from other origins still work server to server, but browsers will block them.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.