There was a typo in the Next.js TypeScript custom Document error message: TypeError: The Document class constructor cannot be invoked without using the 'new' keyword

I encountered a problem with my website that has a customized Document by _document.js. When I tried running yarn dev, I received the error:

TypeError: Class constructor Document cannot be invoked without 'new'

I spent a considerable amount of time searching for solutions and went through multiple suggestions mentioning preset-env within .babelrc. However, I do not have any babel config file.

After some experimentation, changing

"target": "es5"
to
"target": "es5"
resolved the issue. I prefer not to utilize es6 in my tsconfig.

What steps should I take next? (I am new to next.js but well-versed in js and react.js)

UPDATE

Here is an excerpt from my _document.tsx:

import Document, {
    Html,
    Head,
    Main,
    NextScript,
    DocumentContext,
} from 'next/document'
import settings from '../utils/settings/settings'

class MyDocument extends Document {
    render() {
        return (
            <Html lang="fa">
                <!-- Code snippet omitted for brevity -->
            </Html>
        )
    }
}

export default MyDocument

This is my tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": false,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve"
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules"]
}

Answer №1

By implementing the fork-ts-checker-webpack-plugin, I was able to ensure type checking before the build process, among other benefits outlined in its documentation. Interestingly, removing this plugin resolved the issue at hand.

Answer №2

Dealing with a similar problem, I found a solution that worked for me. Copy the code snippet below and save it as a standard .js file.

This trick was something I picked up from a TypeScript tutorial in the past and thankfully remembered when faced with the same issue in another project.

//your imports //

class CustomDocument extends Document {
  //give this a shot 
  static async getInitialProps(ctx) {
    const initialData = await Document.getInitialProps(ctx);
    return { ...initialData };
  }



// Insert your code here //
}

export default CustomDocument

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

Retrieve properly formatted text from the editor.document using the VSCode API

I have been working on creating a personalized VSCode extension that can export the current selected file contents as a PDF. Although PrintCode exists, it does not fit my specific needs. The snippet of code I am currently using is: const editor = vscode.w ...

Click on an element in Angular to toggle it

A function in my codebase is responsible for toggling a specific section within a div element. Currently, there are a total of 3 sections available in the app. The functionality is implemented in the app.component.ts file: show = false; toggle() { ...

Navigating VSCode for Correct Import Setup

My root app directory has a structure consisting of the following folders: /app/ /environments/ Within the /app/ folder, there is a file named Helper.ts located in the helpers/ subdirectory: /app/helper/Helper.ts Inside this file, I attempted to import ...

Acquiring a public image asset within the Next.js project directory with a specified loader configuration path

Background I recently initiated a Next.js project that requires fetching image assets from two distinct locations: In the public directory of the repository: <Image src="/logo.png" width={50} height={50} alt='Logo' layout="fix ...

Next.js rewrites are functioning properly, however, there seems to be an issue with locating the Javascript

I am currently in the process of setting up multiple Vercel/Next.js projects under one domain, as recommended in this helpful guide. Given that each of my apps have unique requirements, it makes sense for me to separate them into their own projects. The ...

Leverage the power of Typescript to flatten a JSON model with the help of Class

Currently, I'm exploring how to utilize the class transformer in TypeScript within a Node.js environment. You can find more information about it here: https://github.com/typestack/class-transformer My goal is to flatten a JSON structure using just on ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

Create a function that takes in a function as an argument and generates a new function that is identical to the original function, except it has one

I want to establish a function called outerFn that takes another function (referred to as innerFn) as a parameter. The innerFn function should expect an object argument with a mandatory user parameter. The main purpose of outerFn is to return a new functio ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Discovering the generic type from an optional parameter within a constructor

Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "und ...

Adjusting slidesPerView based on screen size in Ionic: A step-by-step guide

Recently, I encountered an interesting challenge while working on my ionic project. I had successfully created a slider using ion-slides to display multiple products. Everything was working perfectly for the portrait view with 1.25 slides per view (slide ...

Is the nodejs pm2 server consuming excessive resources?

When I request a website in my browser, the server specifications are 2GB RAM and dual core Ubuntu based. I have hosted the website using pm2, but it seems like the node.js app is not performing well. Have you tried restarting or reinstalling it? I have ...

Tips for transforming Http into HttpClient in Angular 5 (or higher than 4.3)

I have successfully implemented code using Http and now I am looking to upgrade it to use the latest HttpClient. So far, I have taken the following steps: In App.module.ts: imported { HttpClientModule } from "@angular/common/http"; Added HttpClientModul ...

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...

@tanstack/react-query: Cannot find a QueryClient, please provide a QueryClientProvider to set one

Issue Statement: The error I am encountering only occurs in production (next.js) and not consistently, but rather sporadically. Within my next.js project, I am utilizing the package @tanstack/react-query. Occasionally, in production, without warning, I en ...

Error Message: "Unexpected use of Hook in react-hook-form"

I am still getting acquainted with react hook form so I have encountered a minor issue. To my surprise, Controllers are unable to handle values as numbers. At first, this was frustrating, but after some searching, I stumbled upon this helpful github issue ...

The function getServerSideProps is not defined in the NextJS environment

I am facing an issue where I need to pass an array called initialPosts into my Home function using getServerSideProps, but the props are showing up as undefined. Despite trying various solutions, none of them seem to work. In getServerSideProps, I have us ...

typescript declaring a namespace with a restricted identifier

I have created a custom Http client in typescript with the following definition: declare namespace Http { type HttpOptions = ...; type HttpPromise<T> = ... function get<T>(url: string, options?: HttpOptions): HttpPromise<T>; ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...

Discovering a locator based on the initial portion of its value

Here's a piece of code that is used to click on a specific locator: await page.locator('#react-select-4-option-0').click(); Is there a way to click on a locator based on only the initial part of the code, like this: await page.locator(&apos ...