# Allow Only Chosen REST API Namespaces for Visitors

> Blocks REST API routes for logged-out visitors except the namespaces you list (for example oEmbed, contact forms and the WooCommerce Store API), shrinking the public attack surface without breaking front-end features.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: rest-api, hardening, api
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/sec-rest-namespace-allowlist/

## Code

```php
// Namespaces visitors may use.
$wpide_public_namespaces = array( 'oembed/1.0', 'contact-form-7/v1', 'wc/store', 'wc/store/v1', 'wpide/v1', 'jetpack/v4' );

add_filter( 'rest_pre_dispatch', function ( $result, $server, $request ) use ( $wpide_public_namespaces ) {
    if ( null !== $result || is_user_logged_in() ) {
        return $result;
    }

    $route = ltrim( $request->get_route(), '/' );

    if ( '' === $route ) {
        return new WP_Error( 'rest_forbidden', 'The REST API index is not available.', array( 'status' => 401 ) );
    }

    foreach ( $wpide_public_namespaces as $namespace ) {
        if ( 0 === strpos( $route, trim( $namespace, '/' ) . '/' ) || trim( $namespace, '/' ) === $route ) {
            return $result;
        }
    }

    return new WP_Error( 'rest_forbidden', 'Authentication required.', array( 'status' => 401 ) );
}, 10, 3 );
```

## Notes

Add the namespace of any plugin feature that stops working for visitors; the namespace is the first one or two parts of the route, such as contact-form-7/v1.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Allow Only Chosen REST API Namespaces for Visitors" 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/
