Generating Graphql types for React using graphql-codegen when Apollo Server is in production mode: A step-by-step guide

Everything functions perfectly when backend mode is set to NODE_ENV: development, but in production mode I encounter an error with graphql-codegen:

Error on local web server:

Apollo Server does not allow GraphQL introspection, but the query contains _schema or _type. To enable introspection, pass introspection: true to ApolloServer in production.

Error on production web server:

Schema failed to load from https://example.com/graphql, reason being unable to verify the first certificate. GraphQL Code Generator supports:

  • ES Modules and CommonJS exports (export as default or named export "schema")
  • Introspection JSON File
  • URL of GraphQL endpoint
  • Multiple files with type definitions (glob expressions)
  • String in config file

Front-end codegen.yml:

schema: ${REACT_APP_GRAPHQL_URL}
documents:
 - './src/GraphQL/queries/query.ts'    
 - './src/GraphQL/mutations/mutation.ts'
overwrite: true
generates:
  ./src/generated/graphql.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      skipTypename: false
      withHooks: true
      withHOC: false
      withComponent: false

Front-end devDependencies:

{
    "@graphql-codegen/cli": "^1.20.1",
    "@graphql-codegen/typescript": "^1.20.2",
    "@graphql-codegen/typescript-operations": "^1.17.14",
    "@graphql-codegen/typescript-react-apollo": "^2.2.1"
}

npm scripts:

{
    "generate": "graphql-codegen -r dotenv/config --watch --config codegen.yml",
    "prebuild": "graphql-codegen -r dotenv/config --config codegen.yml"
}

./src/generated/ directory has been added to .gitignore

Answer №1

After encountering a problem, I found a solution by adding an introspection plugin and separating the codegen.yml file into two separate files:

  • codegen-generate-schema-json
  • codegen-generate-typescript
devDependencies: {"@graphql-codegen/introspection": "^1.18.1"}

In the codegen-generate-typescript.yml:

schema: graphql.schema.json
documents:
  - './src/GraphQL/queries/query.ts'
  - './src/GraphQL/mutations/mutation.ts'
overwrite: true
generates:
  ./src/generated/graphql.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      skipTypename: false
      withHooks: true
      withHOC: false
      withComponent: false

In the codegen-generate-schema-json.yml:

schema: ${REACT_APP_GRAPHQL_URL}
overwrite: true
generates:
  ./graphql.schema.json:
    plugins:
      - introspection

Therefore, the ./graphql.schema.json file needs to be committed and used as the schema source instead of a URI.

If you have any better suggestions, feel free to share them!

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

Prevent the thread from executing by utilizing a callback block

In my setup, I've implemented an ExpressJS middleware to verify the user's IP in the database and block further responses if there have been more than 7 failed login attempts within the last hour. To prevent unnecessary database queries, I added ...

Tips for effectively timing out a Node.js Oracle DB connection that fails to respond

I am currently utilizing Npm Oracle in my Node.js application. I am facing an issue where my compiler hangs while trying to connect to the Oracle database, causing a thread to get stuck. I need to implement a timeout mechanism as my client cannot wait for ...

Awaiting fulfillment - Promise remains pending as loop executes queries

I have a scenario where I receive an array containing multiple data elements and need to perform a query for each element in the array. However, this is resulting in a promise pending response. How can I resolve this issue? What could be causing it? getFa ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Empty endpoint authorization for Azure Bot

Background : Currently, I am engaged in a project involving a bot on Azure. I have set up a "bot channel registration" to establish an endpoint for receiving messages from Skype for Business. This endpoint is hosted on our server, and while we are able to ...

Encountered issues during deployment on Heroku platform using npm and Java

Previously, I had challenges installing a Java module on localhost but managed to resolve it using the steps outlined in this post: https://github.com/nodejs/node/issues/10289. It worked well on localhost, and now I am attempting to deploy my app on Heroku ...

When typing declarations are used, they clarify whether the entity being referenced is an Object or

I am currently working on aligning the Dockerode run typings to match the actual implementation. The issue arises when I invoke run as TypeScript consistently identifies the return value as a Promise. It seems that TypeScript is having trouble distinguish ...

I encountered an issue when trying to establish a connection between the environment and mongoose

This code is found in my .env file: DB_URL=mongodb://localhost:27017/ecomm The connection.js file contains the following code: const mongoose=require('mongoose') const {DB_URL}=process.env console.log(process.env) async function createConnectio ...

Using the MERN stack in conjunction with Socket for MongoDB provides the ability to display real-time data on the frontend directly

As I work on setting up a website using the MERN stack, my backend will continuously fetch data from APIs and sockets to save it in a MongoDB database. For the frontend React, I aim to display and update this data in real-time using Socket. I have concern ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map') This particular error occurred during the page generation process. Any console logs will appear in the term ...

The ForEach function does not execute actions on every individual object, but rather only once

I am currently developing a Deck building application for a card game. In addition, I have set up a database to manage the cards that I sell and play with. The deck builder tool I created allows me to deplete the stock of sellable cards when adding them to ...

Can you switch out the double quotation marks for single quotation marks?

I've been struggling to replace every double quote in a string with a single quote. Here's what I have tried: const str = '1998: merger by absorption of Scac-Delmas-Vieljeux by Bolloré Technologies to become \"Bolloré.'; console ...

Utilizing Angular routes within a Node.js application deployed on Heroku

I've been working on deploying an AngularJS project to Heroku. The app functions perfectly fine locally and when using heroku local web. However, upon attempting to access it, I encounter the error TypeError: response.sendFile is not a function. Ser ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

Transmitting Data via Socket.io: Post it or Fetch it!

I am struggling to send data via POST or GET in socket.io without receiving any data back. My goal is to send the data externally from the connection. Take a look at the code snippets below: Server-side code: app.js io.sockets.on('connection', ...

Attempting to understand the findings of the npm audit

Context Upon running the npm audit command on an old ReactJS project that we recently revisited after a year, a summary of 356 vulnerabilities was obtained (321 low, 20 moderate, 14 high, 1 critical) across 11345 scanned packages. Executing npm audit fix ...

What is the best way to utilize multiple models under a single root in ReactJS?

Greetings! I currently have a root structure in the following code snippet: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <button >Platform</button> <button >Game</button> < ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

The Correct Approach for Implementing Error Handling in a Node.js API Server

In my Node.js API server, I encountered an issue with error handling. To tackle this problem, I developed a module specifically for error handling. When in development mode, this module sends JSON objects containing errors to the API client. Here is an exa ...