### Complete Subscription Setup Example Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/subscriptions.mdx A full example demonstrating the integration of Express, Apollo Server, and WebSockets. ```ts import { ApolloServer } from '@apollo/server'; import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'; import { expressMiddleware } from '@as-integrations/express5'; import { createServer } from 'http'; import express from 'express'; import { makeExecutableSchema } from '@graphql-tools/schema'; import { WebSocketServer } from 'ws'; import { useServer } from 'graphql-ws/use/ws'; import cors from 'cors'; import resolvers from './resolvers'; import typeDefs from './typeDefs'; // Create the schema, which will be used separately by ApolloServer and // the WebSocket server. const schema = makeExecutableSchema({ typeDefs, resolvers }); // Create an Express app and HTTP server; we will attach both the WebSocket // server and the ApolloServer to this HTTP server. const app = express(); const httpServer = createServer(app); // Create our WebSocket server using the HTTP server we just set up. const wsServer = new WebSocketServer({ server: httpServer, path: '/subscriptions', }); // Save the returned server's info so we can shutdown this server later const serverCleanup = useServer({ schema }, wsServer); ``` -------------------------------- ### Set up Apollo Server with Express Middleware Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/express-middleware.mdx This example demonstrates the complete setup for integrating Apollo Server with an Express application. It includes necessary installations, imports, server initialization, and middleware configuration for handling requests, CORS, and JSON parsing. Ensure you have installed `@apollo/server`, `@as-integrations/express5`, `express`, `graphql`, and `cors`. ```typescript // npm install @apollo/server @as-integrations/express5 express graphql cors import { ApolloServer } from '@apollo/server'; import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'; import { expressMiddleware } from '@as-integrations/express5'; import express from 'express'; import http from 'http'; import cors from 'cors'; import { typeDefs, resolvers } from './schema'; interface MyContext { token?: string; } // Required logic for integrating with Express const app = express(); // Our httpServer handles incoming requests to our Express app. // Below, we tell Apollo Server to "drain" this httpServer, // enabling our servers to shut down gracefully. const httpServer = http.createServer(app); // Same ApolloServer initialization as before, plus the drain plugin // for our httpServer. const server = new ApolloServer({ typeDefs, resolvers, plugins: [ApolloServerPluginDrainHttpServer({ httpServer })], }); // Ensure we wait for our server to start await server.start(); // Set up our Express middleware to handle CORS, body parsing, // and our expressMiddleware function. app.use( '/', cors(), express.json(), // expressMiddleware accepts the same arguments: // an Apollo Server instance and optional configuration options expressMiddleware(server, { context: async ({ req }) => ({ token: req.headers.token }), }), ); // Modified server startup await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve), ); console.log(`🚀 Server ready at http://localhost:4000/`); ``` -------------------------------- ### start Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/apollo-server.mdx Starts the Apollo Server instance. This method triggers schema fetching for federated gateways and calls `serverWillStart` handlers for all installed plugins. It throws an error if schema fetching fails or if any plugin handler throws an error. ```APIDOC ## `start()` ### Description Starts the Apollo Server instance. This method triggers schema fetching for federated gateways and calls `serverWillStart` handlers for all installed plugins. It throws an error if schema fetching fails or if any plugin handler throws an error. ### Method `start()` ### Parameters None ``` -------------------------------- ### Deployment Output Example Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/lambda.mdx Example console output following a successful deployment. ```bash > serverless deploy > Deploying apollo-lambda to stage dev (us-east-1) > ✔ Service deployed to stack apollo-lambda-dev (187s) > .............. > endpoints: > POST - https://ujt89xxyn3.execute-api.us-east-1.amazonaws.com/dev/ > GET - https://ujt89xxyn3.execute-api.us-east-1.amazonaws.com/dev/ > functions: > graphql: apollo-lambda-dev-graphql > Monitor all your API routes with Serverless Console: run "serverless --console" ``` -------------------------------- ### Install Subscription Dependencies Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/subscriptions.mdx Install the necessary packages for WebSocket support. ```bash npm install graphql-ws ws @graphql-tools/schema ``` -------------------------------- ### Start Apollo Server Standalone Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/standalone.mdx Use `startStandaloneServer` for basic Apollo Server setups. It handles server creation and listening on a specified port. ```typescript import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; import { typeDefs, resolvers } from './schema'; interface MyContext { token?: String; } const server = new ApolloServer({ typeDefs, resolvers }); const { url } = await startStandaloneServer(server, { context: async ({ req }) => ({ token: req.headers.token }), listen: { port: 4000 }, }); console.log(`🚀 Server ready at ${url}`); ``` -------------------------------- ### start Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/apollo-server.mdx The async `start` method instructs Apollo Server to prepare to handle incoming operations. It should be called before integrating the server with frameworks or starting to accept requests, with exceptions for serverless environments and testing. ```APIDOC ## `start` The async `start` method instructs Apollo Server to prepare to handle incoming operations. > Call `start` **only** if you are using a framework integration for a non-serverless environment (e.g., [`expressMiddleware`](./express-middleware)). > > - If you're using a serverless framework integration (such as Lambda), you **shouldn't** call this method before passing your server into the integration function. Your serverless integration function will take care of starting your server for you. > > - If you're using `startStandaloneServer` you do **not** need to start your server before [passing it directly to `startStandaloneServer`](./standalone). Always call `await server.start()` _before_ passing your server into your integration function and starting to accept requests: ```ts const server = new ApolloServer({ typeDefs, resolvers, }); await server.start(); app.use( '/graphql', cors(), express.json(), expressMiddleware(server), ); ``` This allows you to react to Apollo Server startup failures by crashing your process instead of starting to serve traffic. If you are testing your server using [`executeOperation`](../testing/testing/) (i.e., you're not actually starting an HTTP server), you don't need to call `start()` because `executeOperation` will do that for you. ``` -------------------------------- ### Install Mocking Dependencies Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/testing/mocking.mdx Install the necessary packages for schema mocking as development dependencies. ```bash npm install --save-dev @graphql-tools/mock @graphql-tools/schema ``` -------------------------------- ### Install graphql-subscriptions Package Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/subscriptions.mdx Command to install the library required for PubSub functionality. ```shell npm install graphql-subscriptions ``` -------------------------------- ### Execute a GET request with curl Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/workflow/requests.md A command-line example to send a GET request with URL-encoded parameters. ```sh curl --request GET \ https://rover.apollo.dev/quickstart/products/graphql?query=query%20GetBestSellers%28%24category%3A%20ProductCategory%29%7BbestSellers%28category%3A%20%24category%29%7Btitle%7D%7D&operationName=GetBestSellers&variables=%7B%22category%22%3A%22BOOKS%22%7D ``` -------------------------------- ### Install and Build Project Source: https://github.com/apollographql/apollo-server/blob/main/DEVELOPMENT.md Initializes the project dependencies and builds the source code. ```bash npm install ``` ```bash npm i ``` -------------------------------- ### Install Apollo Gateway Packages Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/using-federation/apollo-gateway-setup.mdx Install the necessary packages for setting up an Apollo Server gateway. This includes @apollo/gateway, @apollo/server, and graphql. ```shell npm install @apollo/gateway @apollo/server graphql ``` -------------------------------- ### Install Serverless CLI Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/lambda.mdx Install the Serverless CLI globally to facilitate deployment to AWS. ```bash npm install -g serverless ``` -------------------------------- ### Install and Configure Usage Reporting Plugin Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/builtin-plugins.md Demonstrates how to manually install the usage reporting plugin and set a non-default option for sending variable values. ```typescript import { ApolloServer } from "@apollo/server"; import { ApolloServerPluginUsageReporting } from '@apollo/server/plugin/usageReporting'; const server = new ApolloServer({ typeDefs, resolvers, plugins: [ // Sets a non-default option on the usage reporting plugin ApolloServerPluginUsageReporting({ sendVariableValues: { all: true }, }), ], }); ``` -------------------------------- ### Setup Apollo Server with Serverless Express Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/lambda.mdx Use this setup to create a fully functioning Lambda server that works in a variety of AWS features, enabling custom HTTP behavior. Ensure you have @apollo/server, @as-integrations/express5, and @vendia/serverless-express installed. ```ts const { ApolloServer } = require('@apollo/server'); const { expressMiddleware } = require('@as-integrations/express5'); const serverlessExpress = require('@vendia/serverless-express'); const express = require('express'); const cors = require('cors'); const server = new ApolloServer({ typeDefs: 'type Query { x: ID }', resolvers: { Query: { x: () => 'hi!' } }, }); server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests(); const app = express(); app.use(cors(), express.json(), expressMiddleware(server)); exports.graphqlHandler = serverlessExpress({ app }); ``` -------------------------------- ### Create a Data Source Class for Reservations Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/fetching-data.mdx Define a class to manage database connections and fetching reservation data. This example shows initializing a database connection and methods to get user and reservation details. ```typescript export class ReservationsDataSource { private dbConnection; private token; private user; constructor(options: { token: string }) { this.dbConnection = this.initializeDBConnection(); this.token = options.token; } async initializeDBConnection() { // set up our database details, instantiate our connection, // and return that database connection return dbConnection; } async getUser() { if (!this.user) { // store the user, lookup by token this.user = await this.dbConnection.User.findByToken(this.token); } return this.user; } async getReservation(reservationId) { const user = await this.getUser(); if (user) { return await this.dbConnection.Reservation.findByPk(reservationId); } else { // handle invalid user } } //... more methods for finding and creating reservations } ``` -------------------------------- ### Configure Standalone Server Context and Port Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/standalone.mdx This example shows how to configure the context function to extract a token from headers and set the listening port to 4000 when starting a standalone Apollo Server. ```typescript import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; import { typeDefs, resolvers } from './schema'; interface MyContext { token?: String; } const server = new ApolloServer({ typeDefs, resolvers }); const { url } = await startStandaloneServer(server, { context: async ({ req }) => ({ token: req.headers.token }), listen: { port: 4000 }, }); console.log(`🚀 Server ready at ${url}`); ``` -------------------------------- ### Install @apollo/datasource-rest Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/fetching-rest.mdx Install the necessary package for using RESTDataSource. ```bash npm install @apollo/datasource-rest ``` -------------------------------- ### Install Apollo Server dependencies Source: https://github.com/apollographql/apollo-server/blob/main/README.md Install the required packages for Apollo Server and the core GraphQL algorithms. ```bash npm install @apollo/server graphql ``` -------------------------------- ### Install Apollo Server and Express dependencies Source: https://github.com/apollographql/apollo-server/blob/main/README.md Run these commands to install the required packages for Apollo Server and Express integration. ```bash npm install @apollo/server @as-integrations/express5 graphql express cors ``` ```bash npm install --save-dev @types/cors @types/express ``` -------------------------------- ### Server Lifecycle: startupDidFail Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/plugins-event-reference.mdx The `startupDidFail` hook is triggered if the server fails to start, for example, due to schema loading errors or errors in `serverWillStart` or `renderLandingPage` hooks. It receives the error that caused the startup failure. ```APIDOC ## startupDidFail Plugin Event ### Description Triggered if the server fails to start due to errors in schema loading or plugin hooks like `serverWillStart` or `renderLandingPage`. ### Method `startupDidFail` ### Parameters - `error` (Error) - The error that caused the startup failure. ### Request Example ```ts const server = new ApolloServer({ plugins: [ { async serverWillStart() { // Simulate an error during startup throw new Error('Failed to initialize server'); }, startupDidFail(error) { console.error('Server startup failed:', error); } } ], }); ``` ### Response None. ``` -------------------------------- ### Start Express Server Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/mern.mdx Command to start the Express server. After running, the console should output 'Server is running on port: 5050'. ```bash npm start ``` -------------------------------- ### Start Apollo Server Standalone Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/standalone.mdx Use this function to start an Apollo Server instance for prototyping. It requires an ApolloServer instance and returns the URL the server is listening on. ```typescript import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; const server = new ApolloServer({ typeDefs, resolvers }); // `startStandaloneServer` returns a `Promise` with the // the URL that the server is listening on. const { url } = await startStandaloneServer(server); //highlight-line ``` -------------------------------- ### Apollo Server Plugin Example with willResolveField Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/plugins-event-reference.mdx Demonstrates how to implement a plugin that logs the execution time and result of each resolved field. This setup requires the requestDidStart hook to return an executionDidStart hook, which in turn returns the willResolveField hook. ```typescript const server = new ApolloServer({ /* ... other necessary configuration ... */ plugins: [ { async requestDidStart(initialRequestContext) { return { async executionDidStart(executionRequestContext) { return { willResolveField({source, args, contextValue, info}) { const start = process.hrtime.bigint(); return (error, result) => { const end = process.hrtime.bigint(); console.log(`Field ${info.parentType.name}.${info.fieldName} took ${end - start}ns`); if (error) { console.log(`It failed with ${error}`); } else { console.log(`It returned ${result}`); } }; } } } } } } ] }) ``` -------------------------------- ### Install Express and Apollo Integration Packages Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/standalone.mdx Before integrating with Express, install the necessary packages: Express, Apollo's Express middleware, and CORS. ```bash npm install @as-integrations/express5 express cors ``` -------------------------------- ### Initialize ApolloServer Instance Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/getting-started.mdx Create an ApolloServer instance with schema definitions and resolvers, then start it using startStandaloneServer. ```ts // The ApolloServer constructor requires two parameters: your schema // definition and your set of resolvers. const server = new ApolloServer({ typeDefs, resolvers, }); // Passing an ApolloServer instance to the `startStandaloneServer` function: // 1. creates an Express app // 2. installs your ApolloServer instance as middleware // 3. prepares your app to handle incoming requests const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }); console.log(`🚀 Server ready at: ${url}`); ``` -------------------------------- ### Implement a Complete Subgraph Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/using-federation/api/apollo-subgraph.mdx A full example showing type definitions, entity resolvers, and server initialization for a subgraph. ```ts import gql from 'graphql-tag'; import { ApolloServer } from '@apollo/server'; import { buildSubgraphSchema } from '@apollo/subgraph'; const typeDefs = gql` type Query { me: User } type User @key(fields: "id") { id: ID! username: String } `; const resolvers = { Query: { me() { return { id: '1', username: '@ava' }; }, }, User: { __resolveReference(user, { fetchUserById }) { return fetchUserById(user.id); }, }, }; const server = new ApolloServer({ schema: buildSubgraphSchema({ typeDefs, resolvers }), }); ``` -------------------------------- ### Check installed @apollo/gateway version Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/using-federation/apollo-gateway-setup.mdx Use `npm list` to verify the currently installed version of the `@apollo/gateway` library in your project. ```bash npm list @apollo/gateway ``` -------------------------------- ### Install global-agent for Proxy Configuration Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/security/proxy-configuration.md Install the `global-agent` package using npm. This package helps in setting up global support for environment variable-based proxy configuration. ```bash npm install global-agent ``` -------------------------------- ### Example codegen.yml configuration Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/workflow/generate-types.mdx A sample configuration file for defining how GraphQL Code Generator processes your schema. ```yaml # This configuration file tells GraphQL Code Generator how ``` -------------------------------- ### Apollo Server 3 Standalone Server Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/migration-from-v3.mdx Example of setting up a standalone Apollo Server 3 application. ```typescript import { ApolloServer } from 'apollo-server'; import { typeDefs, resolvers } from './schema'; interface MyContext { token?: String; } const server = new ApolloServer({ typeDefs, resolvers, context: async ({ req }) => ({ token: req.headers.token }), }); const { url } = await server.listen(4000); console.log(`🚀 Server ready at ${url}`); ``` -------------------------------- ### Combined subgraph implementation Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/using-federation/apollo-subgraph-setup.mdx A complete example integrating schema definition, resolvers, and server startup. ```ts import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; import gql from 'graphql-tag'; import { buildSubgraphSchema } from '@apollo/subgraph'; const typeDefs = gql` extend schema @link( url: "https://specs.apollo.dev/federation/v2.0" import: ["@key", "@shareable"] ) type Query { me: User } type User @key(fields: "id") { id: ID! username: String } `; const resolvers = { Query: { me() { return { id: '1', username: '@ava' }; }, }, User: { __resolveReference(user, { fetchUserById }) { return fetchUserById(user.id); }, }, }; const server = new ApolloServer({ schema: buildSubgraphSchema({ typeDefs, resolvers }), }); const { url } = await startStandaloneServer(server); console.log(`🚀 Server ready at ${url}`); ``` -------------------------------- ### Define a GraphQL schema excerpt Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/resolvers.mdx Example schema structure demonstrating fields that can utilize default resolvers. ```graphql type Book { title: String } type Author { books: [Book] } ``` -------------------------------- ### RESTDataSource HTTP Methods Example Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/fetching-rest.mdx Provides examples of using the convenience HTTP methods (GET, POST, PUT, PATCH, DELETE) provided by RESTDataSource. Note the use of encodeURIComponent for safe URL path construction. ```typescript class MoviesAPI extends RESTDataSource { override baseURL = 'https://movies-api.example.com/'; // GET async getMovie(id) { return this.get( `movies/${encodeURIComponent(id)}`, // path ); } // POST async postMovie(movie) { return this.post( `movies`, // path { body: { movie } }, // request body ); } // PUT async newMovie(movie) { return this.put( `movies`, // path { body: { movie } }, // request body ); } // PATCH async updateMovie(movie) { return this.patch( `movies`, // path { body: { id: movie.id, movie } }, // request body ); } // DELETE async deleteMovie(movie) { return this.delete( `movies/${encodeURIComponent(movie.id)}`, // path ); } } ``` -------------------------------- ### assertStarted Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/apollo-server.mdx Ensures that the Apollo Server instance has started before accepting requests. This method is intended for use by framework integrations. ```APIDOC ## `assertStarted()` ### Description Ensures that the Apollo Server instance has started before accepting requests. This method is intended for use by framework integrations. ### Method `assertStarted()` ### Parameters None ``` -------------------------------- ### Initialize JavaScript project file Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/getting-started.mdx Create the main entry point file for a JavaScript-based Apollo Server application. ```bash touch index.js ``` -------------------------------- ### Apollo Server 3 Express Setup Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/migration-from-v3.mdx This is the Apollo Server 3 code structure using apollo-server-express. Ensure you have apollo-server-express, apollo-server-core, express, and graphql installed. ```typescript // npm install apollo-server-express apollo-server-core express graphql import { ApolloServer } from 'apollo-server-express'; import { ApolloServerPluginDrainHttpServer } from 'apollo-server-core'; import express from 'express'; import http from 'http'; import { typeDefs, resolvers } from './schema'; interface MyContext { token?: String; } const app = express(); const httpServer = http.createServer(app); const server = new ApolloServer({ typeDefs, resolvers, context: async ({ req }) => ({ token: req.headers.token }), plugins: [ApolloServerPluginDrainHttpServer({ httpServer })], }); await server.start(); server.applyMiddleware({ app }); await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve)); console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`); ``` -------------------------------- ### Implement Apollo Server with Express Source: https://github.com/apollographql/apollo-server/blob/main/README.md A complete example of setting up an Apollo Server instance within an Express application using top-level await. ```javascript import { ApolloServer } from '@apollo/server'; import { expressMiddleware } from '@as-integrations/express5'; import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer' import express from 'express'; import http from 'http'; import cors from 'cors'; // The GraphQL schema const typeDefs = `#graphql type Query { hello: String } `; // A map of functions which return data for the schema. const resolvers = { Query: { hello: () => 'world', }, }; const app = express(); const httpServer = http.createServer(app); // Set up Apollo Server const server = new ApolloServer({ typeDefs, resolvers, plugins: [ApolloServerPluginDrainHttpServer({ httpServer })], }); await server.start(); app.use( cors(), express.json(), expressMiddleware(server), ); await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve)); console.log(`🚀 Server ready at http://localhost:4000`); ``` -------------------------------- ### Apollo Server 5 Express Setup with expressMiddleware Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/migration-from-v3.mdx This is the equivalent Apollo Server 5 code using expressMiddleware. Install @apollo/server, express, graphql, cors, and @as-integrations/express4. Note the use of cors and express.json middleware. ```typescript // npm install @apollo/server express graphql cors import { ApolloServer } from '@apollo/server'; import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'; import { expressMiddleware } from '@as-integrations/express4'; import express from 'express'; import http from 'http'; import cors from 'cors'; import { typeDefs, resolvers } from './schema'; interface MyContext { token?: String; } const app = express(); const httpServer = http.createServer(app); const server = new ApolloServer({ typeDefs, resolvers, plugins: [ApolloServerPluginDrainHttpServer({ httpServer })], }); await server.start(); app.use('/graphql', cors(), express.json(), expressMiddleware(server, { context: async ({ req }) => ({ token: req.headers.token }), }), ); await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve)); console.log(`🚀 Server ready at http://localhost:4000/graphql`); ``` -------------------------------- ### Build Application with npm Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/azure-functions.mdx Use this command to build your application before deployment. ```bash npm run build ``` -------------------------------- ### Initialize GraphQL Code Generator Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/workflow/generate-types.mdx Run the interactive initialization command to generate the configuration file. ```bash npx graphql-code-generator init ``` -------------------------------- ### Install a specific version of @apollo/gateway Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/using-federation/apollo-gateway-setup.mdx Use `npm install` with a version specifier (e.g., `@2.0.0`) to update or install a particular version of `@apollo/gateway`, even if it exceeds your current dependency constraints. ```bash npm install @apollo/gateway@2.0.0 ``` -------------------------------- ### Initialize Node.js Project Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/getting-started.mdx Initialize a new Node.js project with npm and set the package type to module for ES module support. ```bash npm init --yes && npm pkg set type="module" ``` -------------------------------- ### Install TypeScript Dependencies Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/getting-started.mdx Install TypeScript and Node.js types as development dependencies for your project. ```bash npm install --save-dev typescript @types/node ``` -------------------------------- ### Configuring Default Landing Pages Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/plugin/landing-pages.mdx Demonstrates how to configure default landing page plugins (local and production) based on the NODE_ENV environment variable. ```APIDOC ## Configuring Default Landing Pages ### Description This section shows how to configure the default landing page plugins for Apollo Server, allowing you to customize their behavior based on the environment. ### Method Instantiation and Configuration within `ApolloServer` constructor. ### Endpoint N/A (Configuration within server setup) ### Parameters N/A ### Request Example ```ts import { ApolloServer } from '@apollo/server'; import { ApolloServerPluginLandingPageLocalDefault, ApolloServerPluginLandingPageProductionDefault, } from '@apollo/server/plugin/landingPage/default'; const server = new ApolloServer({ typeDefs, resolvers, plugins: [ // Install a landing page plugin based on NODE_ENV process.env.NODE_ENV === 'production' ? ApolloServerPluginLandingPageProductionDefault({ graphRef: 'my-graph-id@my-graph-variant', footer: false, }) : ApolloServerPluginLandingPageLocalDefault({ footer: false }), ], }); ``` ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### Serve Custom Landing Page with renderLandingPage Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/plugins-event-reference.mdx Implement a custom landing page by returning an HTML string or an async function that returns HTML from the `renderLandingPage` handler. This handler is defined within the object returned by `serverWillStart`. ```typescript const server = new ApolloServer({ typeDefs, resolvers, plugins: [ { async serverWillStart() { return { async renderLandingPage() { const html = `

Hello world!

`; return { html }; }, }; }, }, ], }); ``` ```typescript const server = new ApolloServer({ /* ... other necessary configuration ... */ plugins: [ { async serverWillStart() { return { async renderLandingPage() { return { async html() { return `Welcome to your server!`; }, }; }, }; }, }, ], }) ``` -------------------------------- ### Initialize Git and Deploy to Heroku Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/heroku.md Initializes a Git repository, sets the Heroku remote, commits your project files, and pushes to Heroku for deployment. ```shell $ git init # existing git repositories can skip this $ heroku git:remote -a $ git add . $ git commit -m "initial apollo server deployment" $ git push heroku # specify your branch name, if necessary ``` -------------------------------- ### Install Undici Dependency Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/security/proxy-configuration.md Install the undici package to enable proxy configuration for Node.js v20 or v22. ```bash npm install undici ``` -------------------------------- ### Install Legacy Incremental Delivery Package Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/workflow/requests.md Install the required package to support the legacy incremental delivery protocol. ```sh npm install @yaacovcr/transform ``` -------------------------------- ### Start Apollo Server Before Integration Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/apollo-server.mdx Call `await server.start()` before passing the server to your framework integration function. This ensures that startup failures are handled by crashing the process, preventing traffic to a non-ready server. ```typescript const server = new ApolloServer({ typeDefs, resolvers, }); await server.start(); app.use( '/graphql', cors(), express.json(), expressMiddleware(server), ); ``` -------------------------------- ### Initialize Apollo Server with Schema and Resolvers Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/resolvers.mdx Initialize an ApolloServer instance by passing your schema definition and resolver map to the constructor. This example includes setting up a basic server with a hardcoded data store. ```javascript import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; // Hardcoded data store const books = [ { title: 'The Awakening', author: 'Kate Chopin', }, { title: 'City of Glass', author: 'Paul Auster', }, ]; // Schema definition const typeDefs = `#graphql type Book { title: String author: String } type Query { books: [Book] } `; // Resolver map const resolvers = { Query: { books() { return books; }, }, }; // Pass schema definition and resolvers to the // ApolloServer constructor const server = new ApolloServer({ typeDefs, resolvers, }); // Launch the server const { url } = await startStandaloneServer(server); console.log(`🚀 Server listening at: ${url}`); ``` -------------------------------- ### Install dependencies for Apollo Server on AWS Lambda Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/lambda.mdx Install the required Apollo Server packages and TypeScript development dependency. ```shell npm install @apollo/server graphql @as-integrations/aws-lambda ``` ```shell npm install -D typescript ``` -------------------------------- ### Establish asynchronous database connections in context Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/context.mdx Shows how to perform asynchronous operations like database connection initialization within the context function. ```ts context: async () => ({ db: await client.connect(), }) // Resolver (parent, args, contextValue, info) => { return contextValue.db.query('SELECT * FROM table_name'); } ``` -------------------------------- ### Initialize HTTP Server Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/subscriptions.mdx Wrap the Express app in an http.Server instance. ```ts // This `app` is the returned value from `express()`. const httpServer = createServer(app); ``` -------------------------------- ### Heroku Procfile for Node.js App Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/heroku.md Defines the command to run when your Heroku app starts. Replace `node index.js` with your actual start command. ```shell web: node index.js ``` -------------------------------- ### Initialize a standalone Apollo Server Source: https://github.com/apollographql/apollo-server/blob/main/README.md Create a basic GraphQL server using the standalone integration. This requires an ES module environment (e.g., .mjs file) to support top-level await. ```javascript import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; // The GraphQL schema const typeDefs = `#graphql type Query { hello: String } `; // A map of functions which return data for the schema. const resolvers = { Query: { hello: () => 'world', }, }; const server = new ApolloServer({ typeDefs, resolvers, }); const { url } = await startStandaloneServer(server); console.log(`🚀 Server ready at ${url}`); ``` -------------------------------- ### Server Lifecycle: renderLandingPage Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/plugins-event-reference.mdx The `renderLandingPage` event allows you to serve a custom landing page. It's fired after `serverWillStart` and at most one plugin can define this handler. The handler should return an object with an `html` property, which can be a string or an async function returning a string. ```APIDOC ## renderLandingPage Plugin Event ### Description Enables serving a custom landing page. This event is fired once after all `serverWillStart` events complete. Only one plugin can define this handler. ### Method `renderLandingPage` ### Parameters None directly, but it's defined within the object returned by `serverWillStart`. ### Request Example ```ts const server = new ApolloServer({ plugins: [ { async serverWillStart() { return { async renderLandingPage() { const html = `

Hello world!

`; return { html }; }, }; }, }, ], }); ``` ### Response An object with an `html` property (string or async function returning string). ``` -------------------------------- ### Install Apollo Server Dependencies Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/mern.mdx Install the necessary packages for Apollo Server and GraphQL integration in your server project. These include graphql, graphql-tag, @apollo/subgraph, and @apollo/server. ```bash npm install graphql graphql-tag @apollo/subgraph @apollo/server ``` -------------------------------- ### Implement serverWillStart Plugin Event Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/plugins-event-reference.mdx Use the `serverWillStart` event to perform actions when Apollo Server begins preparing to serve GraphQL requests. Startup fails if this async method throws. ```typescript const server = new ApolloServer({ /* ... other necessary configuration ... */ plugins: [ { async serverWillStart() { console.log('Server starting!'); } } ] }) ``` -------------------------------- ### startStandaloneServer Function Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/standalone.mdx The startStandaloneServer function initializes and starts an Apollo Server instance. It returns a promise that resolves with the URL the server is listening on. It accepts the ApolloServer instance as the first argument and an optional configuration object as the second. ```APIDOC ## POST /startStandaloneServer ### Description Starts an Apollo Server instance for standalone use, typically for prototyping. ### Method POST ### Endpoint /startStandaloneServer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **server** (ApolloServer) - Required - An instance of ApolloServer to start. - **options** (Object) - Optional - Configuration options for the server. - **context** (Function) - Optional - An asynchronous function to initialize the context for each request. - **listen** (Object) - Optional - Configuration for the server's listening port and host. Defaults to `{port: 4000}`. - **port** (Number) - Optional - The port to listen on. - **host** (String) - Optional - The host to listen on. ### Request Example ```json { "server": "", "options": { "context": "async ({ req }) => ({ token: req.headers.token })", "listen": { "port": 4000 } } } ``` ### Response #### Success Response (200) - **url** (String) - The URL the server is listening on. #### Response Example ```json { "url": "http://localhost:4000/" } ``` ``` -------------------------------- ### Server Lifecycle: serverWillStart Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/plugins-event-reference.mdx The `serverWillStart` event is called once after all `serverWillStart` events run. It can be used to perform periodic tasks or set up resources that need to be available during the server's lifetime. It can also return an object with handlers for other lifecycle events, such as `renderLandingPage` and `schemaDidLoadOrUpdate`. ```APIDOC ## serverWillStart Plugin Event ### Description This event fires once after all `serverWillStart` events have completed. It's useful for setting up periodic tasks or returning handlers for subsequent lifecycle events. ### Method `serverWillStart` ### Parameters None directly, but can return an object with other handlers. ### Request Example ```ts const server = new ApolloServer({ plugins: [ { async serverWillStart() { const interval = setInterval(doSomethingPeriodically, 1000); return { async serverWillStop() { clearInterval(interval); } } } } ] }); ``` ### Response An object containing handlers for other lifecycle events, or void. ``` -------------------------------- ### Install Apollo Server and Azure Functions Dependencies Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/azure-functions.mdx Install the necessary packages for Apollo Server and its Azure Functions integration. Use `-D` for TypeScript development dependencies. ```shell npm install @apollo/server graphql @as-integrations/azure-functions @azure/functions ``` ```shell npm install -D typescript ``` -------------------------------- ### Example Error Response with Custom Details Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/errors.mdx This JSON shows an example error response from Apollo Server, including custom `extensions` like `code` and `argumentName`, along with a `stacktrace`. ```json { "errors": [ { "message": "Invalid argument value", "locations": [ { "line": 2, "column": 3 } ], "path": ["userWithID"], "extensions": { "code": "BAD_USER_INPUT", // highlight-start "argumentName": "id", // highlight-end "stacktrace": [ "GraphQLError: Invalid argument value", " at userWithID (/my-project/index.js:25:13)", " ...more lines..." ] } } ] } ``` -------------------------------- ### Assert Apollo Server Has Started Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/integrations/building-integrations.md Use the assertStarted method to ensure an Apollo Server instance has been started before passing it to an integration. This is crucial for standard integrations to handle startup errors gracefully. ```typescript server.assertStarted('expressMiddleware()'); ``` -------------------------------- ### Initialize Apollo Server instance Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/deployment/lambda.mdx Define the GraphQL schema and resolvers, then instantiate the ApolloServer. ```ts import { ApolloServer } from '@apollo/server'; // The GraphQL schema const typeDefs = `#graphql type Query { hello: String } `; // A map of functions which return data for the schema. const resolvers = { Query: { hello: () => 'world', }, }; // Set up Apollo Server const server = new ApolloServer({ typeDefs, resolvers, }); ``` -------------------------------- ### GET Requests to Apollo Server Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/workflow/requests.md Apollo Server accepts GET requests for queries, with query details provided as URL query parameters. Variables must be a URL-escaped JSON object. ```APIDOC ## GET /graphql ### Description Sends a GraphQL query to the server via an HTTP GET request. Suitable for caching. ### Method GET ### Endpoint /graphql ### Parameters #### Query Parameters - **query** (string) - Required - The GraphQL query string. - **operationName** (string) - Optional - The name of the operation to execute. - **variables** (string) - Optional - A URL-escaped JSON string representing the variables for the query. ### Request Example ```sh curl --request GET \ https://rover.apollo.dev/quickstart/products/graphql?query=query%20GetBestSellers%28%24category%3A%20ProductCategory%29%7BbestSellers%28category%3A%20%24category%29%7Btitle%7D%7D&operationName=GetBestSellers&variables=%7B%22category%22%3A%22BOOKS%22%7D ``` ### Response #### Success Response (200) - **data** (object) - The result of the GraphQL operation. - **errors** (array) - An array of errors, if any occurred. #### Response Example ```json { "data": { "bestSellers": [ { "title": "The Hitchhiker's Guide to the Galaxy" } ] } } ``` ``` -------------------------------- ### Client Subscription Example Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/data/subscriptions.mdx Clients can subscribe to a specific field of the Subscription type using a GraphQL subscription string. This example shows how a client can subscribe to the 'postCreated' field and request specific fields of the 'Post' object. ```graphql subscription PostFeed { postCreated { author comment } } ``` -------------------------------- ### Usage Reporting Plugin - Default Installation Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/api/plugin/usage-reporting.mdx Apollo Server automatically installs and enables the usage reporting plugin with default settings if you provide a graph API key and a graph ref, and your server is not a federated subgraph. This is typically done via environment variables. ```APIDOC ## Default Installation Apollo Server automatically installs and enables this plugin with default settings if you provide a graph API key and a graph ref to Apollo Server and your server is not a federated subgraph. You usually do this by setting the `APOLLO_KEY` and `APOLLO_GRAPH_REF` (or `APOLLO_GRAPH_ID` and `APOLLO_GRAPH_VARIANT`) environment variables. No other action is required. If you don't provide an API key and graph ref, or if your server is a federated subgraph, this plugin is not automatically installed. If you provide an API key but don't provide a graph ref, a warning is logged. You can disable the plugin to hide the warning. If you provide an API key and graph ref but your server is a federated subgraph, a warning is logged. You can disable the plugin to hide the warning. ``` -------------------------------- ### Implement MutationResponse Source: https://github.com/apollographql/apollo-server/blob/main/docs/source/schema/schema.md Example of an object type implementing the MutationResponse interface. ```graphql type UpdateUserEmailMutationResponse implements MutationResponse { code: String! success: Boolean! message: String! user: User } ```