DEV Community

Kishan
Kishan

Posted on

2

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.

Billboard image

Monitor more than uptime.

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay