1

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]);
Mrtsm
  • 35
  • 4

1 Answers1

0

Please refer to..

https://create-react-app.dev/docs/adding-custom-environment-variables/

These environment variables will be defined for you on process.env. For example, having an environment variable named REACT_APP_NOT_SECRET_CODE will be exposed in your JS as process.env.REACT_APP_NOT_SECRET_CODE.

Rich S
  • 3,248
  • 3
  • 28
  • 49
  • I already saw this, but I need my variable to be secret. – Mrtsm May 22 '23 at 13:21
  • 1
    The issue is that a React app will run on the client's machine. So any authentication keys / secrets are easily available to anybody on that machine. Any server keys / tokens should never be passed down to the user's browser. If the user has authenticated, that token should be used to make calls to `myendpoint.dev` not server keys. – Rich S May 22 '23 at 13:25
  • Well, as I'm using Cloudflare Pages, they have their own way of handling environment variables. And my problem is how to get access to these variables from my react app. – Mrtsm May 22 '23 at 13:30