javascriptreactjsreact-nativeenvironment-variables

How to use the package react-native-dotenv with different env files?


I have a react native web app with expo. And I have different env files. For dev and prod.

And I installed the package react-native-dotenv.

So I have a .env file:

GENERATE_SOURCEMAP=false 
REACT_APP_NAME=ddev
API_URL=http://127.0.0.1

and a .env.production file:

REACT_APP_ENV=PRODUCTION
API_URL=https://dierenwelzijndocker.azurewebsites.net 

And I have configured the babel.config.js file:

module.exports = function (api) {
    api.cache(true);
    return {
        presets: ["babel-preset-expo"],
        plugins: [
            "babel-plugin-styled-components-react-native-web",
            [
                "module:react-native-dotenv",
                {
                    envName: "APP_ENV",
                    moduleName: "@env",
                    path: ".env",
                    blocklist: null,
                    allowlist: null,
                    safe: false,
                    allowUndefined: false,
                    verbose: false,
                },
            ],
        ],
    };
};

And I use the @env file in this method:

export const loginRequest = async (email, password) => {
    try {
        const response = await fetch(`${API_URL}/api/user/token/`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                email: email,
                password: password,
            }),
        });

        const data = await response.json();

        if (response.ok) {
            await AsyncStorage.setItem("Token", data.token);
            //
            return true;
        } else {
            throw new Error(data.token);
        }
    } catch (error) {       
        error, "email en of wachtwoord is niet goed ingevuld";
    }
};

And this works for local development.

But now I want to use the production env file. So I can build a package web-build that I can punt on the remote server.

So how to use the other env file: The production env file where the url is for the production environment?

what I have to change?

Question: how to use the production env file for production?


Solution

  • As per this Expo doc page, files are loaded according to standard .env rules. Those rules are listed here.