Terminating SSL


Most production environments use a load balancer or HTTP proxy (such as nginx) to perform SSL termination on behalf of web applications in that environment.

If you're using Apollo Server in an application that must perform its own SSL termination, you can use the https module with the apollo-server-express middleware library .

Here's an example that uses HTTPS in production and HTTP in development:

JavaScript
1import express from 'express';
2import { ApolloServer } from 'apollo-server-express';
3import typeDefs from './graphql/schema';
4import resolvers from './graphql/resolvers';
5import fs from 'fs';
6import https from 'https';
7import http from 'http';
8
9async function startApolloServer() {
10  const configurations = {
11    // Note: You may need sudo to run on port 443
12    production: { ssl: true, port: 443, hostname: 'example.com' },
13    development: { ssl: false, port: 4000, hostname: 'localhost' },
14  };
15
16  const environment = process.env.NODE_ENV || 'production';
17  const config = configurations[environment];
18
19  const server = new ApolloServer({ typeDefs, resolvers });
20  await server.start();
21
22  const app = express();
23  server.applyMiddleware({ app });
24
25  // Create the HTTPS or HTTP server, per configuration
26  let httpServer;
27  if (config.ssl) {
28    // Assumes certificates are in a .ssl folder off of the package root.
29    // Make sure these files are secured.
30    httpServer = https.createServer(
31      {
32        key: fs.readFileSync(`./ssl/${environment}/server.key`),
33        cert: fs.readFileSync(`./ssl/${environment}/server.crt`)
34      },
35      app,
36    );
37  } else {
38    httpServer = http.createServer(app);
39  }
40
41  await new Promise(resolve => server.listen({ port: config.port }, resolve));
42  console.log(
43    '🚀 Server ready at',
44    `http${config.ssl ? 's' : ''}://${config.hostname}:${config.port}${server.graphqlPath}`
45  );
46  return { server, app };
47}