skip to Main Content

I have a react native web app with expo. And I call at the moment the api call from localhost. But I also have a remote server with of course a other url. How to change the api call for producion?

So I installed

"react-native-dotenv": "^3.4.9",

And I created two env files: dev and production:
.env

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

env.prod

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

And I changed the babel.config.js file:

/* eslint-disable comma-dangle */
/* eslint-disable prettier/prettier */
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 this is the api call:

import { API_URL } from "@env";
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 so this works for local development.

But if I to production. I build a web-build folder with the command > npx expo export:web

and a folder web-build has been created in the root folder. but the api calls are still for localhost.

Question: how to change the api call from local to production?

2

Answers


  1. As written in the documentation you can overwrite the environment used with your package.json command

    // package.json
    {
      "scripts": {
        "start:development": "NODE_ENV=development {your command}",
        "start:production": "NODE_ENV=production {your command}",
      }
    }
    
    Login or Signup to reply.
    1. Use Environment Variables:
    • Define different environment variables for your API endpoints. For
      example,
      you might have a DEV_API_URL for local development and a PROD_API_URL for
      production.
    1. Create Configuration Files:
    • Create configuration files (config.js or similar) where you define these
      environment variables based on the environment.
    1. Import Configuration Based on Environment:
    • Import the appropriate configuration file based on the environment
      (development or production). You might switch between these
      configurations during build time or dynamically based on the runtime environment.

    config.js:

    let apiUrl;
    if (_DEV_) {
      apiUrl = 'http://localhost:3000'; // Your local API URL
    } else {
      apiUrl = 'https://production-api.com'; // Your production API URL
    }
    
    export { apiUrl };
    
    import { apiUrl } from './config';
    // Use apiUrl in your fetch requests
    fetch(`${apiUrl}/endpoint`)
      .then((response) => response.json())
      .then((data) => {
        // Handle data
      })
      .catch((error) => {
        // Handle errors
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search