Same site, logged in โ and REST still treats you as a guest. Without a nonce, cookie authentication acts as if the request is unauthenticated: 401 rest_forbidden. This module shows the three ways to call your own API from inside WordPress.
| Course | WordPress REST API Course ยท Module 6 of 9 ยท Stage 3 "Ship it" |
| Learn | wp_create_nonce( 'wp_rest' ), X-WP-Nonce, apiFetch middlewares, rest_do_request(), expired nonces |
| How | Real code from 4WP FAQ and 4WP Booking, core code where our plugins do not use a function, interview questions after every lesson |
Three ways in
flowchart LR
F["fetch<br/>X-WP-Nonce"] --> API[("Your route")]
AF["apiFetch<br/>nonce middleware"] --> API
PHP["rest_do_request()<br/>no HTTP"] --> API
classDef w fill:#ebf3fb,stroke:#61affe,color:#1e293b
class F,AF,PHP w
Nonces expire: apiFetch fetches a fresh one and retries; with fetch, that is your job.
Before โ after
| Before | After Module 6 |
|---|---|
| 401 for a logged-in admin | X-WP-Nonce from wp_create_nonce( 'wp_rest' ) |
Hardcoded /wp-json/ in JS | rest_url() localized from PHP |
admin-ajax.php for new features | your REST route + apiFetch |
| HTTP request from PHP to the same site | rest_do_request(), permissions still run |
You'll be able to answer
- Why does a logged-in user get 401 from the REST API without a nonce?
- What do createNonceMiddleware and createRootURLMiddleware do?
- When would you use rest_do_request()?