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