aws-amplify / amplify-hosting

AWS Amplify Hosting provides a Git-based workflow for deploying and hosting fullstack serverless web applications.
https://aws.amazon.com/amplify/hosting/
Apache License 2.0
461 stars 116 forks source link

Unable to read non-public environment variables with Vite (Astro) - SSR deployments (specification) #3879

Closed alexnguyennz closed 8 months ago

alexnguyennz commented 11 months ago

Before opening, please confirm:

App Id

d2lbl6s4po2urj

AWS Region

us-east-1

Amplify Hosting feature

SSR

Question

Hi I have a Vite based Astro site that I can't get to read a serverside environment variable - the site is built with the SSR specification (/.amplify-hosting).

Something like this works for PUBLIC starting variables I've set in Amplify's environment variables (no longer needed):

build:
  commands:
    - env | grep -e PUBLIC_ >> .env
    - pnpm run build

But I can't read non-public variables server-side e.g.:

build:
  commands:
    - env | grep -e API_KEY >> .env
    - pnpm run build

Everything works fine locally. Appreciate any assistance with this.

alexnguyennz commented 10 months ago

With a little further testing, it seems I don't need to manually copy PUBLIC environment variables in the build spec actually - any variables starting with PUBLIC_ (Astro renames this from the default VITE_) work by default.

E.g. add the PUBLIC_ environment variable to Amplify and re-deploy the app.

alexnguyennz commented 10 months ago

Passing the environment variables at runtime to the build also does not work on Amplify (but works locally - npm run build and then node entry.mjs in the default folder) e.g. with:

env | grep -e API_KEY >> .env
export $(cat .env) && pnpm run build

The values aren't working at build time at all, whether it's from the .env file (default behaviour) or passed at runtime. I guess the Amplify environment is doing something differently when it comes to building the project with the SSR spec - I can deploy a static site and it works with any serverside variables (without PUBLIC_) just fine.

I think another thing to try would be passing it directly to the node command to run the server (which works locally also), but I can't modify this from the deploy manifest e.g. with entrypoint: "API_KEY=value entry.mjs, it gives an error of the entrypoint can't be found. I'm guessing this configuration isn't used like node ${entrypoint} when Amplify runs the server. I don't see any other way to change this in the docs.

I have a minimal repo here if you would like to check things and deploy on your end.

github-actions[bot] commented 8 months ago

This issue is now closed. Comments on closed issues are hard for our team to see. If you need more assistance, please open a new issue that references this one.

github-actions[bot] commented 8 months ago

This issue has been automatically locked.