The proper method for specifying contextType in NexusJS when integrating with NextJS

I am currently facing a challenge while trying to integrate Prisma and Nexus into NextJS. The issue arises when I attempt to define the contextType in the GraphQL schema.

Here is how I have defined the schema:

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"),
  },
});

When I try to start the development server using npm run dev, I encounter the following error:

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 })],

The content of the context.ts file looks like this:

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

const prisma = new PrismaClient();

export interface Context {
  prisma: PrismaClient;
}

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

Below are the dependencies for my project:

  "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 searching for a solution but haven't been able to find one yet. It seems like the issue might be related to Webpack configurations in NextJS, but as I lack knowledge in that area, I'm unsure about what steps to take next.

Any assistance would be greatly appreciated.

Directory structure of the project:

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

Answer №1

It seems like the issue lies within the path you have specified for your module. If you have defined the schema in a file named schema.ts located in the same directory as your context, then your context type should be structured like this to accurately reflect the relative path:

contextType: {
  module: require.resolve("./context"),
  export: "Context",
}

Answer №2

Here is the solution that worked for me:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to limit the type of the second argument based on the type of the

Within the tutorial Exploring How to Extract Parameter Types from String Literal Types Using TypeScript, a fascinating problem is presented without a solution. function calculate(operation, data) { if (operation === 'add') { return da ...

Guide on deploying a NextJS Node app on Google Cloud Platform via GitHub

I have gone through the following process: First, I installed the `Google Cloud Build app on Github and connected it to Cloud Build. Then, I configured it to work with a specific repository (which happens to be private). Next, I created a trigger in Cloud ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Changes in browser are not reflecting for linked package installed using Yarn or NPM

Scenario In overseeing two key projects, namely main and styles, I encountered a need to modify the styles project and connect it locally to enable these alterations to reflect in the main project. The setup involves a React application utilizing Webpack ...

Looking to launch your Next.js app on an AWS EC2 Ubuntu server? Wondering about the configuration file needed for deployment?

Is there a way to start a Next.js project without using 'npm run start' or 'npm run dev' and access it directly through the build folder? Here is an example of my configuration file: server { listen 80; server_name localhost; lo ...

How can I authenticate to enable access to static files in Next.js?

After exploring various authentication options for Next.js that wouldn't require server-side changes, I aimed to prevent users from accessing the website without entering a password. I conducted tests with NextAuth and managed to block pages using se ...

The `process` variable is not recognized in a Vue/TypeScript component

I've encountered an issue trying to use .env variables in my Vue app. When I ran npm install process, the only syntax that didn't result in an error when importing was: import * as process from 'process'; Prior to this, I received the ...

What is the best way to name a folder in Next.js so that it does not appear in the URL path?

I am working on a nextjs project and I was wondering if there is a way to exclude or bypass a specific subfolder in the URL path. For example, consider this folder structure: src - app - page1 - page.tsx - page2 - page.tsx - pa ...

The execution of a function within context is not triggered

I have developed a decentralized application (dApp) that utilizes a context folder to interact with a smart contract. Within the context, there is a function named loadAuth which verifies if the user is authenticated and then assigns the account state to u ...

Exploring the capabilities of Laravel Webpack Mix and harnessing the power of the

I'm curious about integrating Laravel Webpack Mix with version 5.8 of Laravel. Do I have to include Vue/jQuery in app.js using the extract method in Webpack Mix? Will this result in duplication when loading manifest.js/vendor.js/app.js ? ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

TypeScript does not pay attention to additional properties in the return type of the setState function

I'm completely lost here. I don't understand why typescript allows me to return anything in the setFormValidation call as long as I include the prevState spread in the return object. It seems to ignore all other properties that I return in the ob ...

Utilizing Cloudflare's R2 bucket in conjunction with the Next JS 13 API: A comprehensive guide

Discovering Cloudflare's R2 bucket has been a game-changer for me. The generous free tier is perfect for my personal projects, but I'm struggling to find documentation on how to integrate it with Next.js 13. While there are tutorials available fo ...

The Date Filter is causing a glitch in formatting the date value

I have a variable called dateSubmitted with the value of "dateSubmitted": "07-09-20:11:03:30" Currently, I am utilizing Angular Version 7 Within my HTML code, I am using the date filter to format the date like so: <td> {{element.dateSubmi ...

How can I design a Typescript interface that accommodates both strings and other data types?

I am working on designing an interface that allows for an array of objects and strings to be stored. For instance: const array = [ '', {id: '', labels: ['']} ] I attempted to achieve this using the following code: export ...

Is it no longer possible to export static pages in Next.js 14?

I'm currently experiencing a problem where my CSS styles are not being exported when I try to convert my project into static HTML pages. Here is the configuration in my next.config.js file: ** @type {import('next').NextConfig} */ const next ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

Axios is experiencing challenges in transmitting the cookie

Even after attempting to include {withCredentials: true}, I am still facing issues with sending the cookie to the backend server. return await axios.post(`${API_URL}/posts/category/${id}`, { withCredentials: true }) https://i.stack.imgur.com/Cr8xv.png ...