LoginSignup
1
0

Next.jsのRoute handlersでapollo-serverを起動

Last updated at Posted at 2024-03-09
import { gql } from "apollo/client";
import { ApolloServer } from "@apollo/server";
import { startServerAndCreateNextHandler } from "@as-integrations/next";
import { NextRequest } from "next/server";

export const runtime = "nodejs";

const typeDefs = gql`
  type Mutation {
    hello(name: String): String
  }

  type Query {
    getName: String
  }
`;

const resolvers = {
  Mutation: {
    hello: (name: string) => `Hello, ${name}`,
  },
  Query: {
    getName: () => "seiya",
  },
};

const handler = startServerAndCreateNextHandler<NextRequest>(
  new ApolloServer({
    typeDefs,
    resolvers,
  }),
  {
    context: (req) => Promise.resolve({ req }),
  },
);

export { handler as GET, handler as POST };

runtimeの指定はデフォルトの nodejs であればそのままでいいが、どこかでデフォルトを edge にしていると Can't resolve 'crypto' というエラーが出てしまうので、明示的に nodejs として指定したほうがいい。

元ネタ: https://medium.com/@jareerzeenam/implementing-graphql-and-apollo-server-with-next-js-13-4-a-simple-guide-app-directory-77e38eb697e3

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0