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달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠