Apollo Server Integration for Next.js

repository·main·Indexed 42 days ago

https://github.com/apollo-server-integrations/apollo-server-integration-next

An integration library (@as-integrations/next v4.1.0) that allows Apollo Server to run within a Next.js environment. It supports both the Pages Router (API Routes) and the App Router (Route Handlers) via the startServerAndCreateNextHandler function.

Tokens
1.3K
Snippets
5
Records
6
Agent score
3%

What's inside Apollo Server Next.js Integration

  1. Integrate Apollo Server with Next.js App Router (Route Handlers)

    main

    To use Apollo Server with the Next.js App Router, create a Route Handler file (e.g., app/api/graphql/route.js). Create your ApolloServer instance, pass it to startServerAndCreateNextHandler, and then export the resulting handler as both GET and POST to support GraphQL operations.

    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 };
  2. Integrate Apollo Server with Next.js Pages Router

    main

    To use Apollo Server with the Next.js Pages Router, create an API route file (e.g., pages/api/graphql.js). Initialize an ApolloServer instance and wrap it using startServerAndCreateNextHandler from @as-integrations/next. The resulting handler is exported as the default export of the route file.

    import { ApolloServer } from '@apollo/server';
    import { startServerAndCreateNextHandler } from '@as-integrations/next';
    import { gql } from 'graphql-tag';
    
    const resolvers = {
      Query: {
        hello: () => 'world',
      },
    };
    
    const typeDefs = gql`
      type Query {
        hello: String
      }
    `;
    
    const server = new ApolloServer({
      resolvers,
      typeDefs,
    });
    
    export default startServerAndCreateNextHandler(server);
  3. Provide context to Apollo Server in Next.js

    main

    You can pass a context function as the second argument to startServerAndCreateNextHandler. This function receives the Next.js req and res objects, allowing you to inject request-specific data (like user sessions) into your GraphQL resolvers.

    export default startServerAndCreateNextHandler(server, {
      context: async (req, res) => ({ req, res, user: await getLoggedInUser(req) }),
    });
  4. Use TypeScript with App Router Route Handlers

    main

    When using startServerAndCreateNextHandler with the App Router in TypeScript, you must provide the type of the incoming request object (e.g., NextRequest) as a generic parameter to the function. This ensures the context function receives the correctly typed request object.

    import { NextRequest } from 'next/server';
    
    // req has the type NextRequest
    const handler = startServerAndCreateNextHandler<NextRequest>(server, {
      context: async req => ({ req }),
    });
  5. Use startServerAndCreateNextHandler to integrate Apollo Server with Next.js

    main

    The @as-integrations/next package provides the startServerAndCreateNextHandler function. This function is the primary entrypoint for integrating an Apollo Server instance with Next.js, supporting both the Pages Router (API Routes) and the App Router (Route Handlers). It handles the lifecycle of starting the Apollo Server and converting the resulting request/response cycle into a format compatible with Next.js handlers.

    import { startServerAndCreateNextHandler } from '@as-integrations/next';
    import { ApolloServer } from '@apollo/server';
    
    const server = new ApolloServer({
      typeDefs: `type Query { hello: String }`,
      resolvers: { query: { hello: () => 'world' } },
    });
    
    // Usage in a Next.js Route Handler (App Router)
    export const GET = startServerAndCreateNextHandler(server);
    export const POST = startServerAndCreateNextHandler(server);