How do I correctly reference secret environment variables (process.env.secrets)

120 Views Asked by At

I have set up an AWS amplify app and imported my github project (a web app using Vue/Vite and Supabase as a database).

To protect my supabase address and key I stored both values in secret environment variables as described here: Official documentation

I used the AMPLIFY_SIWA_CLIENT_ID and AMPLIFY_SIWA_PRIVATE_KEY variables and put in the respective values for my supabase project.

When I build the project the build runs through successfully and I see the terminal message during the Backend process:

[INFO]: # Retrieving environment cache...
[INFO]: # Retrieved environment cache
[INFO]: ---- Setting Up SSM Secrets ----
[INFO]: SSM params {"Path":"/amplify/[MY_PROJECT_ID]/staging/","WithDecryption":true}
[INFO]: No live updates for this build run

In my app I then import the process.env.secrets file:

import { createClient } from '@supabase/supabase-js'

interface Secrets {
    AMPLIFY_SIWA_CLIENT_ID?: string;
    AMPLIFY_SIWA_PRIVATE_KEY?: string;
}

let secrets: Secrets = {};
if (process.env.secrets) {
    secrets = JSON.parse(process.env.secrets);
}

const supabaseUrl = secrets.AMPLIFY_SIWA_CLIENT_ID;
const supabaseAnonKey = secrets.AMPLIFY_SIWA_PRIVATE_KEY;

if (!supabaseUrl || !supabaseAnonKey) {
    throw new Error("Supabase URL or Anon Key is missing");
}

export const supabase = createClient(supabaseUrl, supabaseAnonKey)

When I run this, the website loads but then crashes with the error message that the process is not found.

I expected the process.env.secret file to be available during the build and that I can simply import it as shown above. Do you have an idea how to narrow this down?

1

There are 1 best solutions below

0
Webermku On

Ok, after looking at the documentation again and also using ChatGPT I found a way that works.

Firstly, my AWS Amplify build settings were missing the correct export of the secret variables at build, this is the correct command (note, I have created a backend for the app called "staging" which you can see in the call below):

build:
      commands:
        - export VITE_APP_SUPABASE_URL=$(aws ssm get-parameter --name "/amplify/[MY_PROJECT_ID]/staging/VITE_APP_SUPABASE_URL" --with-decryption --query "Parameter.Value" --output text)
        - export VITE_APP_SUPABASE_ANON_KEY=$(aws ssm get-parameter --name "/amplify/[MY_PROJECT_ID]/staging/VITE_APP_SUPABASE_ANON_KEY" --with-decryption --query "Parameter.Value" --output text)
        - yarn run build
        - npm run build

Secondly, Vite needs the .env variables to start with "VITE_" in the standard configuration so I created new secretstring variables in the Prameter Store. Finally, the --with-decryption syntax shown above is needed to get the decrypted string.