如何获取AWS Amplify Pull Request预览URL作为构建时环境变量?
Hey there! I get that you're new to AWS Amplify and need a way to dynamically pull in that auto-generated preview URL for your PR builds instead of hardcoding it—let's break this down clearly:
Key Background: Amplify's Auto-Injected Environment Variable
First off, AWS Amplify Console automatically injects a dedicated environment variable into every PR preview build. You don't need to manually set this up—it's included out of the box for preview deployments triggered by GitHub PRs.
The Variable You Need
The auto-generated preview URL is stored in the AWS_AMPLIFY_PREVIEW_URL environment variable during the build process. This value is the unique, AWS-hosted URL for that specific PR's preview environment.
How to Use This Variable in Your App
Depending on your frontend framework or build setup, here's how to access it:
Direct Access in Build Scripts: You can reference
$AWS_AMPLIFY_PREVIEW_URLdirectly in your build commands (e.g., in yourpackage.jsonscripts or Amplify's build settings). For example, adding a debug line to verify it works:echo "Current Preview URL: $AWS_AMPLIFY_PREVIEW_URL"Framework-Specific Prefixing: Many frontend frameworks (like React, Vue, or Angular) require environment variables to have a specific prefix to be accessible in client-side code. For React, this is
REACT_APP_—so you'll need to map the Amplify variable to a prefixed one:- Go to your Amplify Console app → Build Settings → Environment Variables
- Add a new variable with:
- Key:
REACT_APP_PREVIEW_URL - Value:
$AWS_AMPLIFY_PREVIEW_URL
- Key:
- Save the settings. Now you can access the preview URL in your React code via
process.env.REACT_APP_PREVIEW_URL.
Verify the Variable Works
To make sure the variable is being injected correctly, check your Amplify build logs. Look for the debug line (if you added it) or search for AWS_AMPLIFY_PREVIEW_URL—you should see the full preview URL listed there.
Note on Your GitHub Issue
I noticed you've already opened an issue in the Amplify Console repository for this. Keep an eye on that thread for any official updates or edge-case guidance, but the steps above should fully resolve your current need to avoid hardcoding the preview URL.
内容的提问来源于stack exchange,提问作者Moritz Schmitz v. Hülst

