Below is a simple example of how to add an Authorization Header Token to a fetch() request in React:
const fetchSecretData = ()=> {
const URL = 'https://js-craft.io/secret_data.php'
const headers = { 'Authorization': 'secret_token' };
fetch(URL, {headers})
.then(response => response.json())
.then(data => setSecretData(data.data));
}
The fetchSecretData() method will make a call to the secret_data.php service, and it will receive an answer only if the Authorization header is set to the correct value.
Using the second argument of the fetch() API we can supply request options such as the authorization tokens.

Below is the full code of the React example:
const App = () => {
const [secretData, setSecretData] = useState(null);
const fetchSecretData = ()=> {
const headers = { 'Authorization': 'secret_token' };
fetch('https://js-craft.io/secret_data.php', {headers})
.then(response => response.json())
.then(data => setSecretData(data.data));
}
return (
<div>
<button onClick={fetchSecretData}>
š Press here for a secret movie spoiler
</button>
<h3>{secretData}</h3>
</div>
);
}
You can see the live example running on Github Pages, and I've added to the GitHub repository also the code for the PHP service.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js