• v3 (latest)
  • Integrations
  • AWS Lambda

Integration with AWS Lambda

AWS Lambda is a serverless computing platform that makes it easy to build applications that run on the AWS cloud. GraphQL Yoga is platform agnostic so they can fit together easily.

Installation

yarn add graphql
yarn add aws-lambda
yarn add graphql-yoga

Example

graphql.ts

import { createYoga, createSchema } from 'graphql-yoga'
import { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda'
 
const yoga = createYoga<{
  event: APIGatewayEvent
  lambdaContext: Context
}>({
  // You need to specify the path to your lambda function
  graphqlEndpoint: '/my-lambda',
  schema: createSchema({
    typeDefs: /* GraphQL */ `
      type Query {
        greetings: String
      }
    `,
    resolvers: {
      Query: {
        greetings: () =>
          'This is the `greetings` field of the root `Query` type'
      }
    }
  })
})
 
export async function handler(
  event: APIGatewayEvent,
  lambdaContext: Context
): Promise<APIGatewayProxyResult> {
  const response = await yoga.fetch(
    event.path + '?' + new URLSearchParams(event.queryStringParameters as Record<string, string> || {}).toString(),
    {
    {
      method: event.httpMethod,
      headers: event.headers as HeadersInit,
      body: event.body
        ? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')
        : undefined
    },
    {
      event,
      lambdaContext
    }
  )
 
  const responseHeaders: Record<string, string> = {}
 
  response.headers.forEach((value, name) => {
    responseHeaders[name] = value
  })
 
  return {
    statusCode: response.status,
    headers: responseHeaders,
    body: await response.text(),
    isBase64Encoded: false
  }
}

You can also check a full example on our GitHub repository here

Last updated on January 4, 2023