HomeMethod

Knowledge

Web VitalsTechniquesSnippetsAnswersImpactsBottlenecks

Restrict REST API to authenticated users

  • Security

By default, the WordPress REST API is publicly accessible. Anyone can enumerate usernames via /wp-json/wp/v2/users, read published posts, and probe your site’s structure. For traditional WordPress sites that don’t serve a decoupled frontend, there’s no reason to expose this data.

restrict-rest-api.php
<?php
/**
 * Restrict REST API to Authenticated Users
 *
 * By default, the WordPress REST API exposes user data, post content, and
 * site metadata to anonymous requests. This is useful for headless setups
 * but a privacy concern for traditional sites. This snippet requires
 * authentication for all REST API requests except the root namespace
 * discovery endpoint.
 *
 * Usage: Add to functions.php. Remove if you use a headless frontend,
 *        public API consumers, or plugins that rely on unauthenticated REST.
 *
 * @category security
 * @language php

 *
 * @author Adame Dahmani https://adame.io
 * @support Support my family project: https://adame.io/fundraiser
 */
add_filter( 'rest_authentication_errors', function ( $result ) {
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }

    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            'Authentication required.',
            [ 'status' => 401 ]
        );
    }

    return $result;
} );

This returns a 401 error for all unauthenticated REST API requests. Remove this snippet if you use a headless frontend, mobile app, or any plugin that exposes public REST endpoints (like WooCommerce Store API).

Support our family now