Accessing environment variables at build time
To access an environment variable during a build, edit your build settings to include the environment variable in your build commands.
Each command in your build configuration runs inside a Bash shell. For more information
on working with environment variables in Bash, see Shell Expansions
To edit build settings to include an environment variable
-
Sign in to the AWS Management Console and open the Amplify console
. -
In the Amplify console, choose Hosting, then choose Build settings.
-
In the App build specification section, choose Edit.
-
Add the environment variable to your build command. You should now be able to access your environment variable during your next build. This example changes the npm's behavior (BUILD_ENV) and adds an API token (TWITCH_CLIENT_ID) for an external service to an environment file for later use.
build: commands: - npm run build:$BUILD_ENV - echo "TWITCH_CLIENT_ID=$TWITCH_CLIENT_ID" >> backend/.env
-
Choose Save.
Making environment variables accessible to server-side runtimes
A Next.js server component doesn't have access to your app's environment variables by default. This behavior is intentional to protect any secrets stored in environment variables that your application uses during the build phase.
To make specific environment variables accessible to Next.js, you must modify the Amplify build specification file to set the environment variables in the environment files that Next.js recognizes. This enables Amplify to load the environment variables before it builds the application. For more information about modifying your build specification, see examples of how to add environment variables in the build commands section.