Igor Simic
5 years ago

Enable CORS on Wordpress REST API

If you try to access Wordpress REST API from a different domain  (or from app) you will probably see a message like this:
CORS policy: Request header field ... is not allowed by Access-Control-Allow-Headers. By Default Wordpress is preventing access from non trusted domains.
But if you have a SPA page or an app which should access WP REST API then we have to enable CORS on Wordpress REST API.

We will do that with  by settings couple of header params.This can be easily done by calling action "rest_api_init":
function add_custom_headers() {

    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce,Content-Type, X-Requested-With');
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );

        return $value;
    } );
add_action( 'rest_api_init', 'add_custom_headers', 15 );
By enabling these custom headers you are exposing your WP REST API to outside requests which can be not so secure. In order to put some security we have added X-WP-Nonce (which is generated by wordpress) to header and also you should protect your routes with some permission filtering