DEV Community

Kishan
Kishan

Posted on

AWS AppSync: The Game-Changing Access Method For Environment Variables

Excitingggggg news! AWS has just rolled out support for environment variables in AppSync. Let's delve into incorporating this feature in our SAM & Serverless Framework.

Solution

Step1: When defining AppSync, we can now add environment variables similarly to how it's done during Lambda creation. In the properties section, include EnvironmentVariables and add key-value pairs as needed.

Resources:
  UserAppsync:
    Type: "AWS::AppSync::GraphQLApi"
    Properties:
      Name: "user-int-appsync"
      AuthenticationType: "AWS_IAM"
      EnvironmentVariables:
        USERTABLENAME: "user-int-table"
Enter fullscreen mode Exit fullscreen mode

Step2: Having defined the environment in the YAML file, let's access it in our resolver file. Once environment variables are specified, they are passed for both request and response within the ctx (context) of the function parameter

//accessing the environment variable(NEW METHOD)
const tableName = ctx.env.USERTABLENAME
Enter fullscreen mode Exit fullscreen mode

Accessing it is demonstrated below Inside the Resolver:

/**
 * @param {*} ctx - Context
 * @retuns {Object} - Request object
 */

export function request(ctx) {
  //accessing the environment variable(NEW METHOD)
  const tableName = ctx.env.USERTABLENAME
  return {
    operation: 'BatchGetItem',
    tables: {
      [tableName]: { keys },
    },
  };
}

/**
 * @param {*} ctx - Context
 * @retuns {Object} - Response object
 */
export function response(ctx) {
  return {};
}
Enter fullscreen mode Exit fullscreen mode

As discussed, the environment is now passed within the ctx of both request and response. This enhancement simplifies the process of passing and accessing environment variables with the latest updates.

Top comments (0)