Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active January 13, 2022 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/08574e8b387f21ed026557cffc8779d2 to your computer and use it in GitHub Desktop.
Save mishterk/08574e8b387f21ed026557cffc8779d2 to your computer and use it in GitHub Desktop.
Cookie-based authentication when using the WordPress API Fetch NPM package. https://hookturn.io/cookie-based-authentication-wordpress-api-fetch-npm-package/
<?php
add_action('wp_enqueue_scripts', function(){
// Assuming our previous example code is in a script enqueued with the handle `my-script` e.g;
// wp_enqueue_script( 'my-script', … );
// Localise an object containing our nonce:
wp_localize_script( 'my-script', 'myvars', [
'nonce' => wp_create_nonce( 'wp_rest' )
]);
});
import apiFetch from "@wordpress/api-fetch";
// Add the nonce as middleware. This automatically adds the `X-WP-Nonce`
// header to requests.
apiFetch.use( apiFetch.createNonceMiddleware( window.myvars.nonce ) );
apiFetch({
path: '/wp-json/some/endpoint'
}).then((data) => {
// use data here
});
import apiFetch from "@wordpress/api-fetch";
apiFetch({
path: '/wp-json/some/endpoint',
headers: {'X-WP-Nonce': window.myvars.nonce}
}).then((data) => {
// use data here
});
import apiFetch from "@wordpress/api-fetch";
apiFetch({
path: '/wp-json/some/endpoint',
}).then((data) => {
// use data here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment