How retrieve Vercel Environment Variables in Angular? - Stack Overflow

admin2025-04-17  0

I have an Ionic (8.2.4) app using Angular (17.3.12), with Spring Boot as Backend and PostgreSQL as Database:

  • My database is deployed on Supabase.
  • My backend is deployed on Render.
  • My frontend is deployed on Vercel. I created a login page using Simon Grimm's guide: authentication-in-ionic-angular. With this guide, I created an auth.guard and an AuthenticationService, where I initialize Supabase:

    export class AuthenticationService {
      private supabase: SupabaseClient;
      private currentUser: BehaviorSubject<User | null> = new BehaviorSubject(null);
    
      constructor(private router: Router) {
        console.log('environment.SUPABASE_URL', environment.SUPABASE_URL);
        console.log('environment.SUPABASE_KEY', environment.SUPABASE_KEY);
    
        this.supabase = createClient(
          environment.SUPABASE_URL,
          environment.SUPABASE_KEY
        );
      }
    }

However, after deploying to Vercel, and adding the environment variables in Vercel, they are not correctly being retrieved.

What I tried so far:

  • Using process.env directly in environment.prod.ts:
export const environment = {
  production: true,
  BASE_URL: '',
  SUPABASE_URL: process.env['SUPABASE_URL'] || '',
  SUPABASE_KEY: process.env['SUPABASE_KEY'] || '',
};

I have the following 'Uncaught ReferenceError: process is not defined'.

  • Using import.meta.env instead of process.env:

    export const environment = {
      production: true,
      SUPABASE_URL: import.meta?.env?.VITE_SUPABASE_URL || '',
      SUPABASE_KEY: import.meta?.env?.VITE_SUPABASE_KEY || '',
    };

but, Still not working—it does not get the correct values from Vercel.

  • Following this approach from a related question: how to deploy Angular Environment variables in Vercel?I created a config.js file to dynamically generate the environment file:

    const fs = require('fs');
    require('dotenv').config();
    
    const targetPath = './src/environments/environment.prod.ts';
    
    const envConfigFile = `export const environment = {
        production: true,
        BASE_URL: '',
        SUPABASE_URL: '${process.env.SUPABASE_URL || ''}',
        SUPABASE_KEY: '${process.env.SUPABASE_KEY || ''}'
    };`;
    
    fs.writeFile(targetPath, envConfigFile, function (err) {
      if (err) {
        console.error(err);
        throw err;
      }
    });

Still not working—Vercel doesn't inject the variables. How can I correctly retrieve Vercel environment variables in my Angular (Ionic) app? Is there a specific way to inject them at build time in Vercel? This is my repo. Any help would be greatly appreciated! Thanks in advance.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744886070a272542.html

最新回复(0)