React dotenv no capture Server URL and APP ID

I am trying to capture the variables in my dotenv for the moralis authenticator but it does not work. It is not a problem of the variables because if I put them directly, harcoded, it works. What is the proper way to use them in this component?

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { MoralisProvider } from "react-moralis";
require('dotenv').config();
const { MORALIS_SERVER_URL, MORALIS_APP_ID } = process.env;

ReactDOM.render(
  <MoralisProvider serverUrl={MORALIS_SERVER_URL} appId={MORALIS_APP_ID }>
    <App />
    </MoralisProvider>,
  document.getElementById('root')
);

Can you log these variables successfully? You may have to append the keys with REACT_APP_. Adding Custom Environment Variables | Create React App (create-react-app.dev)

Yes. directly function works as <MoralisProvider serverUrl="https//server/blablabla" appId="XXX">

No I mean can you console.log(process.env.MORALIS_SERVER_URL)?

@glad

console:
server url undefined
error:
ReactMoralisError: Provide a "appId" provided to <MoralisProvider>

Use REACT_APP_MORALIS_SERVER_URL instead. Change it in both .env and code, and restart your server.

1 Like

I did what you told me and it works!!!
I do not understand very well why but if you are so kind as to explain it to me I would appreciate it very much.

Itโ€™s just the way React/CRA works. You can read the link I added above.

2 Likes

On a side note, when deploying for a real project, make sure to use a different method e.g. do this on a backend like Node/Express or use the providerโ€™s (e.g. Netlify) way of handling environment variables - otherwise they are bundled with your build.

What is the recommended method for storing and publishing environment variables in moralis static page?

You can hardcore them directly, it is not a problem

1 Like