# Restrict the REST API to Logged-In Users

> Returns an authentication error for REST API requests from visitors who are not logged in, with an allowlist for routes your site needs publicly.

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

## Code

```php
add_filter( 'rest_authentication_errors', function ( $result ) {
    if ( true === $result || is_wp_error( $result ) || is_user_logged_in() ) {
        return $result;
    }

    // Route prefixes that stay public. Add the namespaces your forms, shop or plugins use.
    $public = array( '/contact-form-7/', '/wc/store/', '/oembed/' );
    $route  = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? (string) $GLOBALS['wp']->query_vars['rest_route'] : '';

    foreach ( $public as $prefix ) {
        if ( 0 === strpos( $route, $prefix ) ) {
            return $result;
        }
    }

    return new WP_Error( 'rest_login_required', 'The REST API is only available to logged-in users.', array( 'status' => rest_authorization_required_code() ) );
} );
```

## Notes

Test forms, search and checkout after enabling. Plugins that call the REST API for visitors need their namespace in $public.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Restrict the REST API to Logged-In Users" 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/
