Search⌘ K
AI Features

Using Fetch to Interact With Authenticated REST API Endpoints

Explore how to securely interact with authenticated REST API endpoints by using fetch and Auth0 bearer tokens. Learn to implement HTTP POST requests with access tokens in React's data layer, enabling protected data submission without changing UI components. Understand how to include authorization headers and verify data persistence with correct user authentication.

We'll properly wire up posting questions and answers to our REST API. As part of this work, we will enhance our http function to use a bearer token from Auth0 in the HTTP request. This is because the endpoints for posting questions and answers are protected in the REST API and require a valid bearer token.

All of our changes will be in QuestionsData.ts—our user interface components will be unchanged.

Posting a question to the REST API

We are going to change the implementation for posting a question to use an access token from Auth0:

  1. Let's start by importing the function that gets the access token from Auth0 into QuestionsData.ts:

C#
import { getAccessToken } from './Auth';
  1. Let's change the ... ...