# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rest-api, cors, headless, security
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-rest-cors-origins/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit REST API CORS to Your Own Apps" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
