reactjsnpmionic-frameworkdotenvionic7

How do I get my Ionic/React app to read/load my .env file?


I'm using Ionic 7, React 18, and included dotenv 16.3. I have created a blank ionic application and have added a file alongside package.json (.env)

NODE_ENV=local
REACT_APP_BASE_URL=http://localhost:3000

I have also created a file, src/services.api.ts, which contains

$ cat src/services/api.ts 
import axios from "axios";

const api = axios.create({
 baseURL: process.env.REACT_APP_BASE_URL,
});

However, attempting to load this file results in a

Uncaught ReferenceError: process is not defined
    <anonymous> api.ts:4

error when I access the app after starting it using

ionic serve

What else do I need to do to get ionic to read my .env file?


Solution

  • I assume you are using Vite to build your app. Vite doesn't use Webpack, and therefore, the usual Webpack globals like process aren't available by default.

    Vite exposes env variables on the special import.meta.env object.

    Here's their detailed instruction: https://vitejs.dev/guide/env-and-mode.html