Handling environment variables in a React + Vite app hosted on App Service

Gokul R Dev 351 Reputation points
2024-10-03T06:10:00.69+00:00

Hello, I am using application settings in App Service to store environment variables. How can I use these variables in a React + Vite app, since accessing environment values is through `import.meta.env.

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,930 questions
{count} votes

1 answer

Sort by: Most helpful
  1. ajkuma 28,036 Reputation points Microsoft Employee Moderator
    2024-10-15T18:51:53.3+00:00

    To benefit the community to find the answer quickly, summarizing the solution shared by Gokul.

    Scenario:
    Have a React application built with Vite that is deployed on Azure App Service. Want to manage sensitive information and configuration settings using environment variables, which is set up in the App Service's application settings.

    Ask:
    How can we access the environment variables stored in Azure App Service within React + Vite application, given that Vite uses import.meta.env for accessing environment values?

    Solution:

    Approach/solution that was shared by Gokul R Dev (Thank you)

    In the vite.config.js file add the define property with an object like this

    define: {
        'process.env': process.env
      }
    

    Your final config file should be something like this:

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      build: {
        rollupOptions: {
          // Remove the `external` option or only use it if you have a specific reason.
        }
      },
      define: {
        'process.env': process.env
      }  
    });
    

    This way vite app will be able to access env variables stored in application settings like a node js.

    _

    Please click Accept Answer - it will benefit the community to find the answers quickly._

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.