typescriptwebpackgraphqlnext.jsnexus-prisma

Correct way to define contextType in NexusJS while using NextJS


I trying to get Prisma and Nexus working with NextJS, but I am having some trouble defining the contextType in the GraphQL schema.

I define the schema like this:

export const schema = makeSchema({
  types: [Query, User, Mutation],
  contextType: {
    module: require.resolve("./graphql/context"),
    export: "Context",
  },
  plugins: [nexusPrisma({ experimentalCRUD: true })],
  outputs: {
    typegen: path.join(process.cwd(), "generated", "nexus-typegen.ts"),
    schema: path.join(process.cwd(), "generated", "schema.graphql"),
  },
});

The error occurs when I start the development server by running npm run dev. The error is as follows:

Module not found: Can't resolve './graphql/context'
  46 |   types: [Query, User, Mutation],
  47 |   contextType: {
> 48 |     module: require.resolve("./graphql/context"),
     |            ^
  49 |     export: "Context",
  50 |   },
  51 |   plugins: [nexusPrisma({ experimentalCRUD: true })],

This is the context.ts file:

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export interface Context {
  prisma: PrismaClient;
}

export function createContext(): Context {
  return { prisma };
}

My dependencies are these:

  "dependencies": {
    "@prisma/client": "^2.13.1",
    "apollo-server-micro": "^2.19.1",
    "next": "latest",
    "nexus": "^1.0.0",
    "nexus-plugin-prisma": "^0.27.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@prisma/cli": "^2.13.1",
    "@types/node": "^12.12.21",
    "@types/react": "^16.9.16",
    "@types/react-dom": "^16.9.4",
    "typescript": "^4.1.3"
  },

I have been trying to look for a solution, but for now I am stuck. I think it might have something to do with NextJS and its Webpack configs, but I have absolutely no knowledge about those so I don't really know what to try.

Any help is appreciated.

Project tree:

root
├─ generated
│  ├─ nexus-typegen.ts
│  └─ schema.graphql
├─ graphql
│  ├─ context.ts
│  └─ schema.ts
├─ interfaces
│  └─ index.ts
├─ next-env.d.ts
├─ package-lock.json
├─ package.json
├─ pages
│  ├─ api
│  │  ├─ graphql.ts
├─ prisma
│  └─ schema.prisma
├─ tsconfig.json

Solution

  • This way worked for me:

      contextType: {
        module: path.join(process.cwd(), "graphql", "context.ts"),
        export: "Context",
      }