Next.js API Routes Integration#
Install#
Assuming you already have a Next.js setup with TypeScript
yarn add graphql graphql-ez @graphql-ez/nextjs
pnpm add graphql graphql-ez @graphql-ez/nextjs
npm install graphql graphql-ez @graphql-ez/nextjs
Usage#
Server module
/src/pages/api/graphql.ts
import { ezApp } from '../../ez';
const { apiHandler } = ezApp.buildApp({
// ...
});
export default apiHandler;
EZ App module
/src/ez.ts
import { CreateApp, gql } from '@graphql-ez/nextjs';
export const ezApp = CreateApp({
// You can use any valid GraphQL Schema
schema,
ez: {
plugins: [
// EZ Plugins
],
},
envelop: {
plugins: [
// Envelop Plugins
],
},
// Other Options
});
Build Custom Context#
The Next.js specific arguments are optional since, in some specific contexts, those might not available,
but you can always use the HTTP's IncomingMessage
req
import { CreateApp, BuildContextArgs, InferContext } from '@graphql-ez/nextjs';
function buildContext({ req, next }: BuildContextArgs) {
// IncomingMessage
req;
// NextApiRequest | undefined
next?.req;
return {
foo: 'bar',
};
}
// This snippet allows you to infer the context returned by your 'buildContext' and add it to the EZContext interface
declare module 'graphql-ez' {
interface EZContext extends InferContext<typeof buildContext> {}
}
export const ezApp = CreateApp({
// ...
buildContext,
});
Cross-Origin Resource Sharing (CORS)#
To enable CORS, specify the cors
property in your configuration
CreateApp({
cors: true,
});
Check the cors package for all the available options.
CreateApp({
// Check https://npm.im/cors#configuration-options
cors: {
// ...
},
});