### Example GET Request Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Shows an example of a GET request to the GraphQL endpoint, including URL-encoded query parameters. ```bash curl "http://localhost:3000/api/graphql?query=query%20%7B%20user%28id%3A%20%22123%22%29%20%7B%20id%20name%20%7D%20%7D" ``` -------------------------------- ### App Router Handler Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/00-START-HERE.md Shows how to export GET and POST handlers for the App Router. This pattern uses NextRequest and returns a Response. ```typescript const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Install Dependencies Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Install the necessary packages for Apollo Server integration with Next.js. ```bash npm install @as-integrations/next @apollo/server next ``` -------------------------------- ### App Router Route Handlers Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Example of setting up the Apollo Server handler for Next.js App Router Route Handlers. The context function receives only the request object. ```typescript const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; // Receives: (req: NextRequest) → Response ``` -------------------------------- ### Pages API Routes Handler Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Example of setting up the Apollo Server handler for Next.js Pages API Routes. The context function receives both the request and response objects. ```typescript export default startServerAndCreateNextHandler(server); // Receives: (req: NextApiRequest, res: NextApiResponse) ``` -------------------------------- ### Alternative Server Start (Synchronous Block) Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/IMPLEMENTATION-REFERENCE.md Presents an alternative method for starting the Apollo Server that would block handler creation. This approach is not used in the integration to ensure synchronous handler initialization. ```typescript await server.start(); // Would block handler creation ``` -------------------------------- ### Database Connection Context Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Sets up the context to include a database connection object, which can then be used in resolvers. ```typescript export default startServerAndCreateNextHandler(server, { context: async (req) => ({ db: await getDbConnection(), }), }); ``` -------------------------------- ### Example POST Request Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Demonstrates how to send a POST request with a GraphQL query, variables, and operation name to the endpoint. ```bash curl -X POST http://localhost:3000/api/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query GetUser($id: ID!) { user(id: $id) { id name } }", "variables": { "id": "123" }, "operationName": "GetUser" }' ``` -------------------------------- ### Full Setup for App Router with Types Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md A comprehensive setup for Apollo Server in a Next.js App Router project, including type safety for context and options. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import type { Options } from '@as-integrations/next'; import { ApolloServer, type BaseContext } from '@apollo/server'; import { NextRequest } from 'next/server'; import { gql } from 'graphql-tag'; interface AppContext extends BaseContext { user: User | null; db: Database; } const typeDefs = gql` type Query { me: User } `; const resolvers = { /* ... */ }; const server = new ApolloServer({ typeDefs, resolvers }); const options: Options = { context: async (req: NextRequest): Promise => { const user = await getUser(req); return { user, db }; }, }; const handler = startServerAndCreateNextHandler( server, options ); export { handler as GET, handler as POST }; ``` -------------------------------- ### Example Code Block Format Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MANIFEST.md Illustrates the expected format for code examples within the documentation, emphasizing completeness, type annotations, and error handling. ```typescript // Full, runnable examples // Shows initialization // Includes type annotations // Demonstrates error handling ``` -------------------------------- ### Basic Apollo Server Setup in Next.js App Router Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Initializes Apollo Server and creates a Next.js request handler for the App Router. This is the fundamental setup for integrating GraphQL. ```typescript //app/api/graphql/route.ts import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { NextRequest } from 'next/server'; import { typeDefs, resolvers } from '@/graphql/schema'; const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Minimal Setup for Pages API Route Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md A minimal setup for integrating Apollo Server with a Next.js Pages API Route using the startServerAndCreateNextHandler utility. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer, gql } from '@apollo/server'; const server = new ApolloServer({ typeDefs, resolvers }); export default startServerAndCreateNextHandler(server); ``` -------------------------------- ### GraphQL POST Request Body Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Example of a standard GraphQL POST request body, including query, variables, and operationName. ```json { "query": "query GetUser($id: ID!) { user(id: $id) { id name } }", "variables": { "id": "123" }, "operationName": "GetUser" } ``` -------------------------------- ### GraphQL Response Example (200 OK) Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Example of a successful GraphQL response with data. Errors are included in the response body with a 200 OK status. ```json { "data": { "user": { "id": "123", "name": "Alice" } } } ``` -------------------------------- ### Data Sources Context Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Configures the context with data sources, such as API clients for users and posts, making them available to resolvers. ```typescript export default startServerAndCreateNextHandler(server, { context: async (req) => ({ dataSources: { userAPI: new UserAPI({ baseURL: 'https://api.example.com/users' }), postAPI: new PostAPI({ baseURL: 'https://api.example.com/posts' }), }, }), }); ``` -------------------------------- ### Mutation Success Response Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Example JSON response for a successful GraphQL mutation operation. ```json { "data": { "createUser": { "id": "456", "name": "Bob", "email": "bob@example.com" } } } ``` -------------------------------- ### Pages API Route Example (TypeScript) Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/startServerAndCreateNextHandler.md Use this snippet to integrate Apollo Server with a Next.js Pages API Route. Ensure you have @apollo/server and @as-integrations/next installed. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { gql } from 'graphql-tag'; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello, world!', }, }; const server = new ApolloServer({ typeDefs, resolvers }); export default startServerAndCreateNextHandler(server); ``` -------------------------------- ### Query Success Response Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Example JSON response for a successful GraphQL query operation. ```json { "data": { "user": { "id": "123", "name": "Alice" } } } ``` -------------------------------- ### Context Function Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/00-START-HERE.md Provides an example of a context function that builds an object available to all GraphQL resolvers. It can include user information and database connections. ```typescript context: async (req) => ({ user: await getUser(req), db: database, }) ``` -------------------------------- ### GraphQL Response Example with Errors Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Example of a GraphQL response containing errors. The status code remains 200 OK. ```json { "data": { "user": null }, "errors": [{ "message": "User not found" }] } ``` -------------------------------- ### Authentication Context Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Configures the context to include user information by validating an authorization token from the request headers. ```typescript const server = new ApolloServer({ typeDefs, resolvers }); export default startServerAndCreateNextHandler(server, { context: async (req) => { const token = req.headers.get?.('authorization')?.split(' ')[1]; let user = null; if (token) { try { user = await validateToken(token); } catch (error) { console.error('Token validation failed:', error); } } return { user }; }, }); ``` -------------------------------- ### Handling Apollo Server Initialization Errors Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/errors.md Illustrates how to wrap initialization logic within a plugin to catch and log potential errors during Apollo Server startup. If the server fails to start, all requests will receive error responses. ```typescript import { ApolloServer } from '@apollo/server'; const server = new ApolloServer({ typeDefs, resolvers, plugins: [ { async serverWillStart() { try { // initialization logic } catch (error) { console.error('Server startup error:', error); throw error; // Let Apollo Server handle it } }, }, ], }); export default startServerAndCreateNextHandler(server); // If server fails to start, requests will return error responses ``` -------------------------------- ### Authentication Context Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Configure the request context to include user information after validating an authorization token. This is useful for protecting GraphQL resolvers. ```typescript export default startServerAndCreateNextHandler(server, { context: async (req) => { const token = req.headers.get?.('authorization')?.split(' ')[1]; const user = token ? await validateToken(token) : null; return { user }; }, }); ``` -------------------------------- ### Custom Options Type Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Configure custom options for the Next.js handler, including context. ```typescript const options: Options = { context: async (req: NextRequest) => ({ user: await getUser(req), }), }; ``` -------------------------------- ### App Router Route Handler Example (TypeScript) Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/startServerAndCreateNextHandler.md This example demonstrates integrating Apollo Server with a Next.js App Router Route Handler. It specifies the request type as NextRequest. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { NextRequest } from 'next/server'; import { gql } from 'graphql-tag'; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello, world!', }, }; const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Usage of Options with Custom Context Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Provides an example of how to define and use the Options type with a custom context function for advanced request handling. ```typescript const options: Options = { context: async (req) => ({ user: await getUser(req), }), }; startServerAndCreateNextHandler(server, options); ``` -------------------------------- ### Apollo Server Startup Handling Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Configure Apollo Server to start in the background and handle startup errors by logging them and failing all subsequent requests. This ensures that server initialization issues are caught early. ```typescript server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests() ``` -------------------------------- ### CommonJS Module Import Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Example of importing the integration utility using CommonJS syntax, suitable for Node.js environments. ```javascript const { startServerAndCreateNextHandler } = require('@as-integrations/next'); ``` -------------------------------- ### Combined Context Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Demonstrates combining multiple context properties like user, database connection, data sources, and the request object into a single context object. ```typescript interface AppContext { user?: User; db: Database; dataSources: DataSources; req: NextApiRequest | NextRequest; } export default startServerAndCreateNextHandler(server, { context: async (req, res) => { const user = await getUserFromRequest(req); const db = await getDbConnection(); return { user, db, dataSources: { userAPI: new UserAPI(), postAPI: new PostAPI(), }, req, }; }, }); ``` -------------------------------- ### Configuring Context with Environment Variables Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md You can access environment variables within your context function to configure your application. This example shows how to retrieve an API key and establish a database connection. ```typescript export default startServerAndCreateNextHandler(server, { context: async (req) => { const apiKey = process.env.EXTERNAL_API_KEY; const dbUrl = process.env.DATABASE_URL; return { apiKey, db: await getDbConnection(dbUrl), }; }, }); ``` -------------------------------- ### Partial Success with Errors Response Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Illustrates a JSON response where a query partially succeeds but returns errors for specific fields. ```json { "data": { "user": { "id": "123", "name": null } }, "errors": [ { "message": "Unauthorized: Cannot access name field", "path": ["user", "name"], "extensions": { "code": "UNAUTHENTICATED" } } ] } ``` -------------------------------- ### Pages API Route Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Create a GraphQL endpoint using Pages API Routes in Next.js. Access the GraphQL endpoint at POST /api/graphql. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { gql } from 'graphql-tag'; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'world', }, }; const server = new ApolloServer({ typeDefs, resolvers }); export default startServerAndCreateNextHandler(server); ``` -------------------------------- ### TypeScript Configuration for App Router Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/types.md Example of configuring `startServerAndCreateNextHandler` with TypeScript generics for App Router. It specifies `NextRequest` to ensure type safety for the request object. ```typescript const handler = startServerAndCreateNextHandler(server, { context: async (req: NextRequest) => ({ req }) }); ``` -------------------------------- ### App Router Route Handler Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Create a GraphQL endpoint using App Router Route Handlers in Next.js. Access the GraphQL endpoint at /api/graphql. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { NextRequest } from 'next/server'; import { gql } from 'graphql-tag'; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'world', }, }; const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Apollo Server Context Function Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Configure the context function to create a fresh context object for each request. This object is accessible to all resolvers. ```typescript context: async (req) => ({ // This function is called once per request user: await getUserFromRequest(req), }) ``` -------------------------------- ### Custom Handler Type Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Define a custom GraphQL handler type for the Next.js integration. ```typescript type GraphQLHandler = ( req: NextRequest | Request ) => Promise; const handler: GraphQLHandler = startServerAndCreateNextHandler(server); ``` -------------------------------- ### Apollo Server Integration Test Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/IMPLEMENTATION-REFERENCE.md Sets up an integration test suite for the Apollo Server Next.js integration using `defineIntegrationTestSuite`. It configures the Apollo Server, creates the Next.js handler, and wraps it in an HTTP server for testing. ```typescript defineIntegrationTestSuite( async (serverOptions, testOptions) => { // Create server const server = new ApolloServer(serverOptions); // Create handler const handler = startServerAndCreateNextHandler(server, testOptions); // Get Next.js API resolver (version-specific) const apiResolver = await getApiResolver(); // Wrap in HTTP server for testing const httpServer = createServer((req, res) => apiResolver(req, res, '', handler, {...}, false) ); // Return test interface return { server, url, extraCleanup }; }, { serverIsStartedInBackground: true } ); ``` -------------------------------- ### Define AppContext Extending BaseContext Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Example of defining a custom application context that extends the base Apollo Server context. ```typescript interface AppContext extends BaseContext { user: User; } ``` -------------------------------- ### startServerAndCreateNextHandler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/startServerAndCreateNextHandler.md Creates an HTTP request handler for Next.js API Routes and App Router Route Handlers. It automatically starts the Apollo Server instance and handles incoming GraphQL requests. ```APIDOC ## startServerAndCreateNextHandler ### Description Creates an HTTP request handler compatible with both Next.js Pages API Routes and App Router Route Handlers. It automatically starts the Apollo Server instance and handles incoming GraphQL requests. ### Method Exported as a function. ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. ### Parameters - **server** (`ApolloServer`) - Required - An initialized Apollo Server instance with your schema and resolvers configured. - **options** (`Options`) - Optional - Configuration options object. If omitted, uses an empty context. ### Options #### context - **context** (`ContextFunction`) - Optional - An async function that receives the request object (and response for API Routes) and returns an object that will be available in all resolver functions via the `context` parameter. See Apollo Server docs for `ContextFunction` signature. Default: `async () => ({})`. ### Return Type Returns a handler function that is compatible with both Next.js API Routes and Route Handlers. ```typescript // API Route signature (Pages Router) async function handler( req: HandlerReq, res: NextApiResponse ): Promise // Route Handler signature (App Router) async function handler( req: HandlerReq, res?: undefined ): Promise ``` ### Behavior - **Server Startup**: Automatically starts the Apollo Server instance in the background using `server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests()`. - **Request Handling**: Parses GraphQL requests, executes them, and returns the response. - **Headers & Status Codes**: Automatically manages response headers and HTTP status codes. - **Streaming Responses**: Supports chunked response bodies for subscriptions and multipart responses. ### Throws/Rejects - **Error**: Thrown if an API Route handler is called without passing a `res` object. Message: `"API Routes require you to pass both the req and res object."` ### Usage Examples #### Pages API Route (with TypeScript) ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { gql } from 'graphql-tag'; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello, world!', }, }; const server = new ApolloServer({ typeDefs, resolvers }); export default startServerAndCreateNextHandler(server); ``` #### App Router Route Handler (with TypeScript) ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { NextRequest } from 'next/server'; import { gql } from 'graphql-tag'; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello, world!', }, }; const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` ``` -------------------------------- ### Integration with Authentication Context Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/INDEX.md Configure Apollo Server integration with Next.js to include an authentication context. This example shows how to asynchronously retrieve user data from the request. ```typescript startServerAndCreateNextHandler(server, { context: async (req) => ({ user: await getUser(req), }), }); ``` -------------------------------- ### GraphQL Subscriptions with SSE Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Defines GraphQL schema for subscriptions and a basic resolver structure. This setup is automatically handled by the integration for Server-Sent Events (SSE). ```typescript const typeDefs = gql` type Subscription { messageAdded: Message } `; const resolvers = { Subscription: { messageAdded: { subscribe: async function* () { // Yield values as they arrive }, }, }, }; ``` -------------------------------- ### External API Data Source Setup Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Integrate external APIs as Apollo DataSources within the Next.js handler's context. This allows for organized data fetching from external services. ```typescript import { DataSource } from '@apollo/datasource'; class UserAPI extends DataSource { async getUser(id) { /* ... */ } } export default startServerAndCreateNextHandler(server, { context: async () => ({ dataSources: { userAPI: new UserAPI(), }, }), }); ``` -------------------------------- ### App Router Route Handler Type Safety (TypeScript) Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Example demonstrating type safety for the handler in App Router Route Handlers using TypeScript. ```typescript import { NextRequest } from 'next/server'; const handler = startServerAndCreateNextHandler(server); // handler receives (req: NextRequest) and returns Response ``` -------------------------------- ### Preventing Server Startup Failures with Schema Validation Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/errors.md This example shows how to validate your GraphQL schema early during Apollo Server initialization to prevent startup failures. It catches schema errors and exits the process if validation fails. ```typescript import { buildSchema } from 'graphql'; // Validate schema early try { const schema = buildSchema(typeDefs); const server = new ApolloServer({ schema, resolvers }); } catch (error) { console.error('Schema error:', error); process.exit(1); } ``` -------------------------------- ### Implementing Rate Limiting with Next.js Middleware Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Implement rate limiting for your GraphQL API using Next.js middleware. This example shows how to check against a rate limit function before processing the request. ```typescript // middleware.ts (App Router) import { rateLimit } from './lib/rateLimit'; export async function middleware(request) { if (request.nextUrl.pathname.startsWith('/api/graphql')) { const limited = await rateLimit(request); if (limited) { return new NextResponse('Rate limit exceeded', { status: 429 }); } } } ``` -------------------------------- ### Create Next.js Route Handler (App Router) Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/README.md This snippet demonstrates how to set up a GraphQL API endpoint using Next.js Route Handlers in the App Router. It exports the handler for both GET and POST requests. ```javascript import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; import { gql } from 'graphql-tag'; const resolvers = { Query: { hello: () => 'world', }, }; const typeDefs = gql` type Query { hello: String } `; const server = new ApolloServer({ resolvers, typeDefs, }); const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Start Apollo Server and Create Next.js Handler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/IMPLEMENTATION-REFERENCE.md The core function factory that initializes Apollo Server and creates a handler for Next.js requests. It manages request/response processing for both Pages API Routes and App Router. ```typescript function startServerAndCreateNextHandler< Req extends HandlerRequest = NextApiRequest, Context extends BaseContext = object, >(server: ApolloServer, options?: Options) ``` -------------------------------- ### Context Function Pattern for App Router Route Handlers Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/types.md Example of implementing the `context` function for App Router Route Handlers. It receives a `NextRequest` or `Request` and returns a custom context object. ```typescript // For App Router Route Handlers context: async (req: NextRequest | Request) => ({ req, user: await getUserFromRequest(req), dataSources: { ... } }) ``` -------------------------------- ### Context Function Signature for App Router Route Handlers Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Example of a context function for App Router Route Handlers. It receives `NextRequest` or `Request` and returns an object for the resolver context. ```typescript context: async (req: NextRequest | Request) => { // Return context object return { req, user: await getUserFromRequest(req), // ... other context properties } } ``` -------------------------------- ### Options Type Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Configuration options for `startServerAndCreateNextHandler`, including custom context. ```APIDOC ## Options Type ### Description Configuration options for `startServerAndCreateNextHandler`, including custom context. ### Definition ```typescript interface Options< Req extends HandlerRequest, Context extends BaseContext > { context?: ContextFunction< [Req, Req extends NextApiRequest ? NextApiResponse : undefined], Context >; } ``` ### Type Parameters - `Req`: Request type. - `Context`: Context type. ### Properties - `context` (ContextFunction): Optional function to provide custom context. ### Usage ```typescript const options: Options = { context: async (req) => ({ user: await getUser(req), }), }; startServerAndCreateNextHandler(server, options); ``` ``` -------------------------------- ### getBody Usage Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/getBody.md Demonstrates how to use the getBody function with both Pages API Routes and Route Handlers. The function automatically handles parsing based on the request type and Content-Type header. ```typescript import { getBody } from '@as-integrations/next'; import { NextApiRequest } from 'next'; // For Pages API Routes const body = await getBody(req); // body is already parsed by Next.js console.log(typeof body); // 'object' or 'string' // For Route Handlers const body = await getBody(req); // body is parsed based on content-type console.log(body); // JSON object or string ``` -------------------------------- ### Correcting Type Safety with Apollo Server Next.js Handler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/errors.md This example demonstrates the correct usage of TypeScript generics with `startServerAndCreateNextHandler`. It shows how to specify the expected request type (`NextRequest`) to ensure type safety. ```typescript // ❌ Type error: NextRequest expected const handler = startServerAndCreateNextHandler(server); const result = handler(nextRequest); // Type mismatch // ✅ Correct const handler = startServerAndCreateNextHandler(server); const result = handler(nextRequest); // Type matches ``` -------------------------------- ### Importing Options Type Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Shows how to import the Options type for configuring the startServerAndCreateNextHandler function. ```typescript import type { Options } from '@as-integrations/next'; ``` -------------------------------- ### Importing startServerAndCreateNextHandler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Demonstrates how to import the primary handler function from the '@as-integrations/next' package. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; ``` -------------------------------- ### Custom Context Type Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Define a custom context type for your Apollo Server and integrate it with Next.js handler. ```typescript interface AppContext { user: User | null; db: Database; dataSources: DataSources; } const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server, { context: async (req): Promise => { return { user: await getUser(req), db: new Database(), dataSources: { /* ... */ }, }; }, }); ``` -------------------------------- ### Startup Error Handling Flow Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/IMPLEMENTATION-REFERENCE.md Illustrates the sequence of events when a startup error occurs in Apollo Server within a Next.js application. Errors are logged, requests are failed gracefully, and responses include error details. ```text 1. startServerAndCreateNextHandler() called 2. server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests() 3. Schema validation fails 4. Error logged to console 5. Flag set internally by Apollo Server 6. Next request arrives 7. Apollo Server returns error response in executeHTTPGraphQLRequest() 8. Handler sends error response to client ``` -------------------------------- ### Pages API Route Type Safety Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Example demonstrating type safety for the handler in Pages API Routes. ```typescript import { startServerAndCreateNextHandler } from '@as-integrations/next'; const handler = startServerAndCreateNextHandler(server); // handler receives (req: NextApiRequest, res: NextApiResponse) ``` -------------------------------- ### Using Utilities for Request Analysis Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Demonstrates how to use utility functions like getBody, getHeaders, and isNextApiRequest to analyze incoming requests in Next.js. ```typescript import { getBody, getHeaders, isNextApiRequest, } from '@as-integrations/next'; import { NextApiRequest } from 'next'; async function analyzeRequest(req: unknown) { if (isNextApiRequest(req as NextApiRequest)) { const body = await getBody(req); const headers = getHeaders(req); console.log('API Route request'); } else { console.log('Route Handler request'); } } ``` -------------------------------- ### Running Integration Tests Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Commands to execute the integration's test suite for different Next.js versions. Tests cover core GraphQL functionalities and integration aspects. ```bash npm run test # All Next.js versions npm run test:next16 # Specific version ``` -------------------------------- ### Apollo Server Instance Configuration Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Configure the Apollo Server instance with options like typeDefs, resolvers, plugins, and introspection. Refer to the Apollo Server documentation for a full list of options. ```typescript import { ApolloServer, ApolloServerPlugin } from '@apollo/server'; const server = new ApolloServer({ typeDefs, resolvers, introspection: process.env.NODE_ENV === 'development', plugins: [ { async serverWillStart() { console.log('Server starting up'); }, }, ], }); ``` -------------------------------- ### Main Entry Point Export Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md This snippet shows the main export from the package's entry point file. ```typescript export * from './startServerAndCreateNextHandler'; ``` -------------------------------- ### Instantiate Apollo Server Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Basic instantiation of Apollo Server with a generic type for the application context. ```typescript const server = new ApolloServer({ typeDefs, resolvers }); ``` -------------------------------- ### Type Guard Pattern Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/isNextApiRequest.md Illustrates the TypeScript type guard pattern with `isNextApiRequest`, showing how the `req` type is narrowed within conditional blocks. ```typescript function processRequest(req: NextApiRequest | NextRequest | Request) { if (isNextApiRequest(req)) { // req is NextApiRequest here console.log(req.method); // string console.log(req.query); // Record } else { // req is NextRequest | Request here const body = req.body; // ReadableStream | null const url = req.url; // string } } ``` -------------------------------- ### getHeaders Usage Example Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/getHeaders.md Conceptual usage of the getHeaders function within a Next.js API route or route handler to extract and log request headers. ```typescript import { getHeaders } from '@as-integrations/next'; import { NextApiRequest } from 'next'; // Pages API Route const headers = getHeaders(req); headers.forEach((value, key) => { console.log(`${key}: ${value}`); }); // Route Handler const headers = getHeaders(req); headers.forEach((value, key) => { console.log(`${key}: ${value}`); }); ``` -------------------------------- ### App Router Route Handler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Configure a GraphQL endpoint for the App Router in Next.js. Ensure GET and POST methods are explicitly exported for the handler. ```typescript // app/api/graphql/route.js import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Package.json Exports Configuration Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/IMPLEMENTATION-REFERENCE.md Defines the main entry point, types, and files to be published for the Apollo Server Next.js integration package. Only the contents of the `dist/` directory are included in the npm package. ```json { "main": "dist/index.js", "types": "dist/index.d.ts", "files": ["dist/**/*"] } ``` -------------------------------- ### Querying GraphQL Schema via Introspection Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Introspection queries can be sent via POST requests to the GraphQL endpoint. This example demonstrates querying for type names. ```bash curl -X POST http://localhost:3000/api/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "__schema { types { name } }" }' ``` -------------------------------- ### CORS Configuration with Next.js Middleware Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/API-OVERVIEW.md Configure Cross-Origin Resource Sharing (CORS) headers using Next.js middleware for the App Router. This example allows all origins and methods. ```typescript // middleware.ts (App Router) import { NextResponse } from 'next/server'; export function middleware(request) { const response = NextResponse.next(); response.headers.set('Access-Control-Allow-Origin', '*'); response.headers.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); return response; } export const config = { matcher: '/api/:path*' }; ``` -------------------------------- ### Running Integration Tests Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/IMPLEMENTATION-REFERENCE.md Provides commands to run the integration tests for the Apollo Server Next.js integration against different Next.js versions. Use `npm run test` for all versions or specific commands for targeted testing. ```bash npm run test # All Next.js versions npm run test:next12 # Specific version npm run test:next16 # Latest version ``` -------------------------------- ### Context Function Pattern for API Routes Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/types.md Example of implementing the `context` function for Pages API Routes. It receives `NextApiRequest` and `NextApiResponse` and returns a custom context object. ```typescript // For Pages API Routes context: async (req: NextApiRequest, res: NextApiResponse) => ({ req, res, user: await getUserFromRequest(req), dataSources: { ... } }) ``` -------------------------------- ### Integration with Type Safety for Context Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/INDEX.md Implement type safety for your Apollo Server context when integrating with Next.js. This example defines a specific AppContext type for the context object. ```typescript const handler = startServerAndCreateNextHandler(server, { context: async (req): Promise => ({ user: await getUser(req), db: database, }), }); ``` -------------------------------- ### Pages API Route Handler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Set up a single GraphQL endpoint for the Pages API in Next.js. This handler supports POST for operations and GET for Apollo Sandbox and introspection. ```typescript // pages/api/graphql.js import { startServerAndCreateNextHandler } from '@as-integrations/next'; import { ApolloServer } from '@apollo/server'; const server = new ApolloServer({ typeDefs, resolvers }); export default startServerAndCreateNextHandler(server); ``` -------------------------------- ### Implementing Authentication via Context Function Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/endpoints.md Use the context function in startServerAndCreateNextHandler to process incoming requests, verify authentication tokens, and attach user information to the context. This allows resolvers to access authenticated user data. ```typescript export default startServerAndCreateNextHandler(server, { context: async (req) => { const token = req.headers.get('authorization')?.split(' ')[1]; if (!token) { return { user: null }; } try { const user = await verifyToken(token); return { user }; } catch (error) { return { user: null }; } }, }); ``` -------------------------------- ### Next.js Middleware for CORS and Rate Limiting Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Example of using Next.js middleware to handle Cross-Origin Resource Sharing (CORS) and other request-level configurations not managed by the Apollo Server integration. ```typescript // middleware.ts export function middleware(request) { const response = NextResponse.next(); response.headers.set('Access-Control-Allow-Origin', '*'); response.headers.set('Access-Control-Allow-Methods', 'GET,POST'); return response; } export const config = { matcher: '/api/:path*' }; ``` -------------------------------- ### Context Function Signature for Pages API Routes Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Example of a context function for Pages API Routes. It receives `NextApiRequest` and `NextApiResponse` and should return an object to be merged into the resolver context. ```typescript context: async ( req: NextApiRequest, res: NextApiResponse ) => { // Return context object return { req, res, user: await getUserFromRequest(req), // ... other context properties } } ``` -------------------------------- ### Generic Type Parameters for startServerAndCreateNextHandler Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/ARCHITECTURE.md The `startServerAndCreateNextHandler` function uses generic type parameters `Req` and `Context` to enable full type safety. `Req` specifies the request type (defaulting to `NextApiRequest`), and `Context` allows customization of the context shape passed to Apollo Server. ```typescript startServerAndCreateNextHandler(server, options) ``` -------------------------------- ### Type-Safe Context Configuration for App Router Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/configuration.md Shows how to explicitly define and use a TypeScript interface for the context when working with App Router, ensuring type safety. ```typescript import { NextRequest } from 'next/server'; interface AppContext { user: User | null; req: NextRequest; } const server = new ApolloServer({ typeDefs, resolvers }); const handler = startServerAndCreateNextHandler(server, { context: async (req: NextRequest): Promise => { const user = await getUserFromRequest(req); return { user, req }; }, }); export { handler as GET, handler as POST }; ``` -------------------------------- ### Apollo Server Schema Validation Error Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/errors.md When Apollo Server fails to start due to a missing Query type, validate that your `typeDefs` and `resolvers` are correctly defined before passing them to the `ApolloServer` constructor. ```text Error: Schema must contain a Query type ``` -------------------------------- ### Extending Integration with Apollo Server Plugins Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/ARCHITECTURE.md Demonstrates how to extend the Apollo Server integration by adding custom behavior through Apollo Server plugins. This allows for request lifecycle hooks and error handling. ```typescript const server = new ApolloServer({ typeDefs, resolvers, plugins: [ { async requestDidStart() { /* ... */ }, async didResolveOperation() { /* ... */ }, async didEncounterErrors() { /* ... */ }, }, ], }); ``` -------------------------------- ### Importing getHeaders Function Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Demonstrates importing the getHeaders utility function for accessing request headers. ```typescript import { getHeaders } from '@as-integrations/next'; ``` -------------------------------- ### Basic Configuration with Context Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/README.md Configure the Apollo Server Next.js handler with a custom context function. This function is executed for each request and can be used to fetch user data or database connections. ```typescript startServerAndCreateNextHandler(server, { context: async (req) => ({ user: await getUser(req), db: database, }), }) ``` -------------------------------- ### Usage of startServerAndCreateNextHandler for Pages API Routes and App Router Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/MODULE-EXPORTS.md Illustrates how to use startServerAndCreateNextHandler for both Pages API Routes and App Router Route Handlers, including generic type parameters for advanced context. ```typescript // Pages API Routes export default startServerAndCreateNextHandler(server); // App Router Route Handlers const handler = startServerAndCreateNextHandler(server); export { handler as GET, handler as POST }; ``` -------------------------------- ### Usage Example: Handling Different Next.js Request Types Source: https://github.com/apollo-server-integrations/apollo-server-integration-next/blob/main/_autodocs/api-reference/isNextApiRequest.md Demonstrates how to use `isNextApiRequest` within a handler to conditionally process requests based on whether they originate from a Pages API Route or an App Router Route Handler. ```typescript import { isNextApiRequest } from '@as-integrations/next'; import { NextApiRequest, NextApiResponse } from 'next'; import { NextRequest } from 'next/server'; const handler = async (req: NextApiRequest | NextRequest) => { if (isNextApiRequest(req)) { // TypeScript narrows req to NextApiRequest here console.log(req.query); // This property exists on NextApiRequest // Handle Pages API Route return { body: 'API Route' }; } else { // TypeScript narrows req to NextRequest | Request here console.log(req.headers.get('content-type')); // Request.headers interface // Handle App Router Route Handler return new Response('Route Handler'); } }; ```