Deploying with AWS Lambda
How to deploy Apollo Server with AWS Lambda
AWS Lambda is a service that allows users to run code without provisioning or managing servers. Cost is based on the compute time that is consumed, and there is no charge when code is not running.
This guide explains how to setup Apollo Server 2 to run on AWS Lambda.
Prerequisites
The following must be done before following this guide:
Setup an AWS account
Install the serverless framework from NPM
npm install -g serverless
Setting up your project
Setting up a project to work with Lambda isn't that different from a typical NodeJS project.
First, install the apollo-server-lambda
package:
1npm install apollo-server-lambda graphql
Next, set up the schema's type definitions and resolvers, and pass them to the ApolloServer
constructor like normal. Here, ApolloServer
must be imported from apollo-server-lambda
. It's also important to note that this file must be named graphql.js
, as the config example in a later step depends on the filename.
1// graphql.js
2
3const { ApolloServer, gql } = require('apollo-server-lambda');
4
5// Construct a schema, using GraphQL schema language
6const typeDefs = gql`
7 type Query {
8 hello: String
9 }
10`;
11
12// Provide resolver functions for your schema fields
13const resolvers = {
14 Query: {
15 hello: () => 'Hello world!',
16 },
17};
18
19const server = new ApolloServer({ typeDefs, resolvers });
20
21exports.graphqlHandler = server.createHandler();
Finally, pay close attention to the last line. This creates an export named graphqlHandler
with a Lambda function handler.
Deploying with the Serverless Framework
Serverless is a framework that makes deploying to services like AWS Lambda simpler.
Configuring the Serverless Framework
Serverless uses a config file named serverless.yml
to determine what service to deploy to and where the handlers are.
For the sake of this example, the following file can just be copied and pasted into the root of your project.
1# serverless.yml
2
3service: apollo-lambda
4provider:
5 name: aws
6 runtime: nodejs12.x
7functions:
8 graphql:
9 # this is formatted as <FILENAME>.<HANDLER>
10 handler: graphql.graphqlHandler
11 events:
12 - http:
13 path: graphql
14 method: post
15 cors: true
16 - http:
17 path: graphql
18 method: get
19 cors: true
Running the Serverless Framework
After configuring the Serverless Framework, all you have to do to deploy is run serverless deploy
If successful, serverless
should output something similar to this example:
1> serverless deploy
2Serverless: Packaging service...
3Serverless: Excluding development dependencies...
4Serverless: Uploading CloudFormation file to S3...
5Serverless: Uploading artifacts...
6Serverless: Uploading service .zip file to S3 (27.07 MB)...
7Serverless: Validating template...
8Serverless: Updating Stack...
9Serverless: Checking Stack update progress...
10..............
11Serverless: Stack update finished...
12Service Information
13service: apollo-lambda
14stage: dev
15region: us-east-1
16stack: apollo-lambda-dev
17api keys:
18 None
19endpoints:
20 POST - https://ujt89xxyn3.execute-api.us-east-1.amazonaws.com/dev/graphql
21 GET - https://ujt89xxyn3.execute-api.us-east-1.amazonaws.com/dev/graphql
22functions:
23 graphql: apollo-lambda-dev-graphql
What does serverless
do?
First, it builds the functions, zips up the artifacts, and uploads the artifacts to a new S3 bucket. Then, it creates a Lambda function with those artifacts, and if successful, outputs the HTTP endpoint URLs to the console.
Managing the resulting services
The resulting S3 buckets and Lambda functions can be viewed and managed after logging in to the AWS Console.
To find the created S3 bucket, search the listed services for S3. For this example, the bucket created by Serverless was named
apollo-lambda-dev-serverlessdeploymentbucket-1s10e00wvoe5f
To find the created Lambda function, search the listed services for
Lambda
. If the list of Lambda functions is empty, or missing the newly created function, double check the region at the top right of the screen. The default region for Serverless deployments isus-east-1
(N. Virginia)
Getting request info
To read information about the current request from the API Gateway event (HTTP headers, HTTP method, body, path, ...)
or the current Lambda Context (Function Name, Function Version, awsRequestId, time remaining, ...)
, use the options function. This way, they can be passed to your schema resolvers via the context option.
1const { ApolloServer, gql } = require('apollo-server-lambda');
2
3// Construct a schema, using GraphQL schema language
4const typeDefs = gql`
5 type Query {
6 hello: String
7 }
8`;
9
10// Provide resolver functions for your schema fields
11const resolvers = {
12 Query: {
13 hello: () => 'Hello world!',
14 },
15};
16
17const server = new ApolloServer({
18 typeDefs,
19 resolvers,
20 context: ({ event, context }) => ({
21 headers: event.headers,
22 functionName: context.functionName,
23 event,
24 context,
25 }),
26});
27
28exports.graphqlHandler = server.createHandler();
Modifying the Lambda response (Enable CORS)
To enable CORS, the response HTTP headers need to be modified. To accomplish this, use the cors
options.
1const { ApolloServer, gql } = require('apollo-server-lambda');
2
3// Construct a schema, using GraphQL schema language
4const typeDefs = gql`
5 type Query {
6 hello: String
7 }
8`;
9
10// Provide resolver functions for your schema fields
11const resolvers = {
12 Query: {
13 hello: () => 'Hello world!',
14 },
15};
16
17const server = new ApolloServer({ typeDefs, resolvers });
18
19exports.graphqlHandler = server.createHandler({
20 cors: {
21 origin: '*',
22 credentials: true,
23 },
24});
Furthermore, to enable CORS response for requests with credentials (cookies, http authentication), the allow origin
and credentials
header must be set to true.
1const { ApolloServer, gql } = require('apollo-server-lambda');
2
3// Construct a schema, using GraphQL schema language
4const typeDefs = gql`
5 type Query {
6 hello: String
7 }
8`;
9
10// Provide resolver functions for your schema fields
11const resolvers = {
12 Query: {
13 hello: () => 'Hello world!',
14 },
15};
16
17const server = new ApolloServer({ typeDefs, resolvers });
18
19exports.graphqlHandler = server.createHandler({
20 cors: {
21 origin: true,
22 credentials: true,
23 },
24});
Setting up GraphQL Playground
By default, serverless
will deploy to AWS with the stage
set to development
resulting in an API endpoint at /dev/graphql
.
To allow GraphQL Playground to correctly use the dev
endpoint, add a new endpoint
configuration within the playground
option to the ApolloServer
instantiation options:
1const server = new ApolloServer({
2 typeDefs,
3 resolvers,
4 playground: {
5 endpoint: "/dev/graphql"
6 }
7});
For information on additional configuration options, see GraphQL Playground.