This is a Next.js 12 integration of GraphQL Server. It is early work and has not been extensively tested in production.
It is based on samples provided by @glasser and the official apollo-server-lambda integration.
Apollo Server is a community-maintained open-source GraphQL server that works with many Node.js HTTP server frameworks. Read the docs. Read the CHANGELOG.
Getting Started
This section assumes that you already have a running Next.js project.
npm install apollo-server-nextjs graphql
Create a file named pages/api/graphql.js
, place the following code:
import { ApolloServer, gql } from "apollo-server-nextjs";
import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello world!",
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
});
export default server.createHandler();
export const config = {
api: {
bodyParser: false,
},
};
Then open http://localhost:3000/api/graphql
Modifying the Response (Enable CORS)
To enable CORS the response HTTP headers need to be modified. To accomplish this use the cors
option.
import { ApolloServer, gql } from "apollo-server-lambda";
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello world!",
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
export default server.createHandler({
expressGetMiddlewareOptions: {
cors: {
origin: "*",
credentials: true,
},
},
});
To enable CORS response for requests with credentials (cookies, http authentication) the allow origin header must equal the request origin and the allow credential header must be set to true.
import { ApolloServer, gql } from "apollo-server-lambda";
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello world!",
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
export default server.createHandler({
expressGetMiddlewareOptions: {
cors: {
origin: true,
credentials: true,
},
},
});
Cors Options
The options correspond to the express cors configuration with the following fields(all are optional):
origin
: boolean | string | string[]methods
: string | string[]allowedHeaders
: string | string[]exposedHeaders
: string | string[]credentials
: booleanmaxAge
: number
Principles
GraphQL Server is built with the following principles in mind:
- By the community, for the community: GraphQL Server's development is driven by the needs of developers
- Simplicity: by keeping things simple, GraphQL Server is easier to use, easier to contribute to, and more secure
- Performance: GraphQL Server is well-tested and production-ready - no modifications needed
Anyone is welcome to contribute to GraphQL Server, just read CONTRIBUTING.md, take a look at the roadmap and make your first PR!