I'm using Cloudflare pages to deploy a react app and I'm trying to access my Environment Variables. From Cloudflare Pages docs, I saw that I had to create a middleware function to get the variables, and then in my component, I have to fetch the variables, but I don't seem to make it work so far.
Here's my middleware function:
const authKey = async ({ request, next, env }) => {
const authorization = env.authorization;
await next();
};
export default authKey;
My component where I need to use my key:
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import ShareButtons from './ArticleShare';
import Navbar from './Navbar';
import authKey from '../functions/_middleware';
function Reader({activeCategory}) {
const { id } = useParams();
const [article, setArticle] = useState(null);
const [error, setError] = useState(null);
const navigate = useNavigate();
useEffect(() => {
const fetchAuthKey = async () => {
await authKey({ request: null, next: () => {}, env: process.env });
};
fetchAuthKey();
}, []);
useEffect(() => {
var myHeaders = new Headers();
myHeaders.append("authorization", process.env.authorization);
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch(`myendpoint.dev/id/${id}`, requestOptions)
.then(response => response.json())
.then(data => {
if (data.length > 0) {
setArticle(data[0]);
}
})
.catch(error => setError(error));
}, [id]);