Apollo Server 2 is officially end-of-life as of 22 October 2023.

Learn more about upgrading.

Deploying with Google Cloud Functions


This tutorial helps you deploy Apollo Server to Google Cloud Functions. It uses the following example function handler:

Click to expand
JavaScript
index.js
1const { ApolloServer, gql } = require('apollo-server-cloud-functions');
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
17/*
18Because `NODE_ENV` is a reserved environment variable in Google Cloud Functions
19and it defaults to "production", you need to set both the `playground` and
20`introspection` options to `true` for GraphQL Playground to work correctly.
21*/
22const server = new ApolloServer({
23  typeDefs,
24  resolvers,
25  playground: true,
26  introspection: true,
27});
28
29exports.handler = server.createHandler();

Deploying from the Google Cloud Console

1. Configure the function

From your Google Cloud Console, go to the Cloud Functions page.

Click Create Function. Give the function a name and set the Trigger type to HTTP.

For quick setup and access to the GraphQL endpoint/playground, choose to Allow unauthenticated invocations. To require authentication for this endpoint, you can manage authorized users via Cloud IAM.

Save your configuration changes in the Trigger section. Copy the trigger's URL for later and click Next.

2. Write the API handlers and deploy

Now on the Code page, set the runtime to a currently supported version of Node.js (such as Node.js 14), and set the Entry point to handler.

Paste the example code at the top of this page into the contents of index.js in the code editor.

Edit package.json so that it lists apollo-server-cloud-functions and graphql in its dependencies:

JSON
package.json
1"dependencies": {
2  "apollo-server-cloud-functions": "^2.24.0",
3  "graphql": "^15.5.0"
4}

Click Deploy to initiate deployment. Then, proceed to Testing the function.

Deploying from your local machine

Before proceeding, you need to set up the gcloud SDK:

  1. Install the gcloud SDK

  2. Initialize the gcloud SDK and authenticate your Google account

Next, initialize a new Node.js project by running npm init in an empty directory.

Run npm install apollo-server-cloud-functions graphql to install the necessary dependencies and to include them in the package.json file.

At this point, your package.json should resemble the following:

JSON
1{
2  "name": "apollo-gcloud",
3  "version": "1.0.0",
4  "description": "",
5  "main": "index.js",
6  "scripts": {
7    "test": "echo \"Error: no test specified\" && exit 1"
8  },
9  "author": "",
10  "license": "ISC",
11  "dependencies": {
12    "apollo-server-cloud-functions": "^2.24.0",
13    "graphql": "^15.5.0"
14  }
15}

Create a new file named index.js and paste the sample code at the top of this page into it.

Run the following command to create and deploy the function to Cloud Functions:

Bash
1gcloud functions deploy apollo-graphql-example --entry-point handler --runtime nodejs14 --trigger-http

This creates a function named apollo-graphql-example that you can view from your console's Cloud Functions page

The command asks some configuration questions and prints metadata about your newly created function, which includes the function's trigger URL.

For more information, see the official Cloud Functions docs.

Testing the function

After deployment completes, navigate to your function's trigger URL. If deployment succeeded, GraphQL Playground opens.

If you can't access your trigger URL, you might need to add allAuthenticatedUsers or allUsers permissions to your function.

You can use GraphQL Playground to test the following query:

GraphQL
1query TestQuery {
2  hello
3}

And verify that the following response appears:

JSON
1{
2  "data": {
3    "hello": "Hello world!"
4  }
5}

Getting request details

To obtain information about a currently executing Google Cloud Function (HTTP headers, HTTP method, body, path, etc.) use the context option. This enables you to pass any request-specific data to your server's resolvers.

JavaScript
1const { ApolloServer, gql } = require('apollo-server-cloud-functions');
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: ({ req, res }) => ({
21    headers: req.headers,
22    req,
23    res,
24  }),
25});
26
27exports.handler = server.createHandler();

Modifying the GCF Response (CORS)

To enable CORS, you need to modify your HTTP response headers. To do so, use the cors option:

JavaScript
1const { ApolloServer, gql } = require('apollo-server-cloud-functions');
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});
21
22exports.handler = server.createHandler({
23  cors: {
24    origin: '*',
25    credentials: true,
26  },
27});

To enable CORS response for requests with credentials (cookies, HTTP authentication) the allow origin header must equal the request origin and the allow credential header must be set to true.

JavaScript
1const { ApolloServer, gql } = require('apollo-server-cloud-functions');
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});
21
22exports.handler = server.createHandler({
23  cors: {
24    origin: true,
25    credentials: true,
26  },
27});

CORS Options

The options correspond to the express cors configuration with the following fields(all are optional):

OptionType(s)
originboolean | string | string[]
methodsstring | string[]
allowedHeadersstring | string[]
exposedHeadersstring | string[]
credentialsboolean
maxAgenumber
Feedback

Edit on GitHub

Forums