How to correctly include and reference secret environment variables (AWS Amplify, process.env.secrets)

0

I have set up an AWS amplify app and imported my github project (a web app using Vue 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

Issue

Following the end of the build however, in my app, where I try to import the variables this does not work.

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;

export const supabase = createClient(supabaseUrl, supabaseAnonKey)

The website loads but then crashes with the error message that the value for supabaseUrl is not found.

Question

My question is if this is maybe related to my build settings - do I have to make the secret key call explicit there or do I need to modify my github files/the variable call within my supabase.ts file in my project to allow this to run through?

Many thanks for the help

1 回答
1
已接受的回答

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 Parameter Store. Finally, the --with-decryption syntax shown above is needed to get the decrypted string.

Veritas
已回答 4 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则