Cookie-based authentication when using the WordPress API Fetch NPM package. https://hookturn.io/cookie-based-authentication-wordpress-api-fetch-npm-package/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ) | |
]); | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import apiFetch from "@wordpress/api-fetch"; | |
apiFetch({ | |
path: '/wp-json/some/endpoint', | |
headers: {'X-WP-Nonce': window.myvars.nonce} | |
}).then((data) => { | |
// use data here | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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