How to add Environment Variables in vite.config.js for a React Project
21:19 27 Jan 2023

How can I add Environment Variables in Vite React Project in the vite.config.js file

I wanted to add the proxy_url in the .env file and add it to the environment when deploying. Please have a look below!

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

const proxy_url = "http://localhost:5000/";

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: proxy_url,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^/api/, ""),
      },
    },
  },
});

Some blogs and answers on StackOverflow but they were resolving the same issue for Vue. Those didn't work for me in my Vite-React Project!

javascript reactjs environment-variables vite