šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React fetch data from API with authentication

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.

React fetch data from API with authentication

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *