-1

I have created a .env file then I have written this code: VITE_API_URL=http://localhost:5000/api

I have applied the "VITE_API_URL" environment variable, but it gives an error. I also tried without the VITE prefix, but not remove the error.

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000/api';

The error:

Runtime Error TypeError: Cannot read properties of undefined (reading 'VITE_API_URL') "const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000/api'; export const api = { async request(endpoint: string, options: RequestInit = {}) { const url = `; at src/lib/api.ts:1:38 Bun v1.2.20

bun + react environment variable error

1 Answer 1

2

For Bun projects

If your project uses Bun, do this instead:

Step 1: Install dotenv

bun add dotenv

Step 2: Create a .env file:

VITE_API_URL=http://localhost:5000/api

Step 3: Load it manually in your code:

import 'dotenv/config';

const API_BASE_URL = process.env.VITE_API_URL || 'http://localhost:3000/api';

export const api = {
  async request(endpoint: string, options: RequestInit = {}) {
    const url = `${API_BASE_URL}/${endpoint}`;
    // ...
  },
};

For Vite projects

If this is actually a Vite app (not Bun):

  1. The file must be named .env or .env.local and be at the root of your project.

  2. The variable must start with VITE_.

  3. Restart your dev server after adding or changing .env.

    npm run dev
    
    
  4. Then this line will work fine:

    const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000/api';
    
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.