Published: February 16 2023

React + Fetch - Add Bearer Token Authorization Header to HTTP Request

Below is a quick example of how to add a Bearer Token Authorization Header to an HTTP request in React using fetch() which comes built into all modern browsers.


React Bearer Token

This sends an HTTP GET request to the Test JSON API with the HTTP Authorization header set to a bearer token. The Test JSON API is a fake online REST API that includes a product details route (/products/{id}), the returned product includes an id and name.

After the JSON data is fetched from the API it is assigned to the product state variable and rendered in the component template.

Add Authorization Header

The auth header with bearer token is added to the request by passing a custom headers object (e.g. { headers: { 'Authorization': 'Bearer my-token' } }) as the second parameter to the fetch() function. The second param contains the fetch request options and it supports a bunch of different options for making HTTP requests including setting headers, a complete list is available at https://developer.mozilla.org/docs/Web/API/fetch.

import React, { useState, useEffect } from 'react';

export { App };

function App() {
    const [product, setProduct] = useState(null);

    useEffect(() => {
        const headers = { 'Authorization': 'Bearer my-token' };
        fetch('https://testapi.jasonwatmore.com/products/1', { headers })
            .then(response => response.json())
            .then(data => setProduct(data));
        
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <div>
            <h3 class="p-3 text-center">React Bearer Token with Fetch</h3>
            <div className="card text-center m-3">
                <h5 className="card-header">GET Request with Bearer Token Authorization Header</h5>
                <div className="card-body">Product name: {product?.name}</div>
            </div>
        </div>
    );
}

See the React request with bearer token on StackBlitz at https://stackblitz.com/edit/react-bearer-token-with-fetch


More React Fetch Examples

For more React HTTP examples see React + Fetch - HTTP GET Request Examples.

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by