diff --git a/src/pages/gen2/build-a-backend/functions/index.mdx b/src/pages/gen2/build-a-backend/functions/index.mdx index 0f4bec1f5c7..a2a9504fce9 100644 --- a/src/pages/gen2/build-a-backend/functions/index.mdx +++ b/src/pages/gen2/build-a-backend/functions/index.mdx @@ -91,7 +91,7 @@ Within your function handler, you can access environment variables using the nor ```ts title="amplify/functions/my-demo-function/handler.ts" // highlight-next-line -import { env } from '@env/my-demo-function'; // the import is '@env/' +import { env } from '$amplify/env/my-demo-function'; // the import is '$amplify/env/' export const handler = async (event) => { env. // the env object has intellisense for all environment variables that are available to the function @@ -99,6 +99,26 @@ export const handler = async (event) => { }; ``` + + +At the end of [AWS Cloud Development Kit's (AWS CDK)](https://aws.amazon.com/cdk/) synthesis, Amplify gathers names of environment variables that will be available to the function at runtime and generates the file `.amplify/generated/env/.ts`. + +If you created your project with [`create-amplify`](https://www.npmjs.com/package/create-amplify), then Amplify has already set up your project to use the `env` symbol. + +If you did not, you will need to manually configure your project. Within your `amplify/tsconfig.json` file add a `paths` compiler option: + +```json title="amplify/tsconfig.json" +{ + "compilerOptions": { + "paths": { + "$amplify/*": ["../.amplify/generated/*"] + } + } +} +``` + + + ## Secret access Sometimes it is necessary to provide a secret value to a function. For example, it may need a database password or an API key to perform some business use case. Environment variables should NOT be used for this because environment variable values are included in plaintext in the function configuration. Instead, secret access can be used. @@ -118,7 +138,7 @@ export const myDemoFunction = defineFunction({ You can use this secret value at runtime in your function the same as any other environment variable. However, you will notice that the value of the environment variable is not stored as part of the function configuration. Instead, the value is fetched when your function runs and is provided in memory. ```ts title="amplify/functions/my-demo-function/handler.ts" -import { env } from '@env/my-demo-function'; +import { env } from '$amplify/env/my-demo-function'; export const handler = async (event) => { env.API_KEY; // this is the value of secret named "myApiKey" @@ -148,7 +168,7 @@ This access definition will add the environment variable `myProjectFiles_BUCKET_ Here's an example of how it can be used to upload some content to S3. ```ts title="amplify/functions/my-demo-function/handler.ts" -import { env } from '@env/my-demo-function'; +import { env } from '$amplify/env/my-demo-function'; import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; const s3Client = new S3Client();