I am trying to configure my vite/React app so that we can put the server address in an environment variable.
I am trying to store the server address in env.local
and loading it with loadEnv
but I can't get the environment variables to load.
If I hard code my server address it works fine.
My env.local file just contains
VITE_API_URL=http://120.0.0.1:8080
Here is my vite.config.ts:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import { TanStackRouterVite } from '@tanstack/router-vite-plugin';
import { loadEnv } from 'vite';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
if (!env.VITE_API_URL) {
throw new Error(`VITE_API_URL is not defined <${mode}> ${JSON.stringify(env)}`);
}
return {
plugins: [TanStackRouterVite(), react()],
base: '/app/',
server: {
proxy: {
// '/api': 'http://127.0.0.1:8080', <<-- this works
'/api': env.VITE_API_URL,
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
sourcemap: true,
outDir: 'build',
},
};
});
I am trying to configure my vite/React app so that we can put the server address in an environment variable.
I am trying to store the server address in env.local
and loading it with loadEnv
but I can't get the environment variables to load.
If I hard code my server address it works fine.
My env.local file just contains
VITE_API_URL=http://120.0.0.1:8080
Here is my vite.config.ts:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import { TanStackRouterVite } from '@tanstack/router-vite-plugin';
import { loadEnv } from 'vite';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
if (!env.VITE_API_URL) {
throw new Error(`VITE_API_URL is not defined <${mode}> ${JSON.stringify(env)}`);
}
return {
plugins: [TanStackRouterVite(), react()],
base: '/app/',
server: {
proxy: {
// '/api': 'http://127.0.0.1:8080', <<-- this works
'/api': env.VITE_API_URL,
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
sourcemap: true,
outDir: 'build',
},
};
});
The exception throws. If I remove the exception my calls to the back end won't work.
Share Improve this question asked Nov 19, 2024 at 10:52 ohthepainohthepain 2,0803 gold badges21 silver badges34 bronze badges 2- "The exception throws" - Which exception? You haven't added any in the question. Please edit and add the full error/exception as text inside it. – DarkBee Commented Nov 19, 2024 at 11:06
- this is answered stackoverflow/questions/79203480/… – Irrfan23 Commented Nov 19, 2024 at 13:00
1 Answer
Reset to default -1Place your .env.local file in the root directory of your project, at the same level as your vite.config.ts file