What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application.

My Attempts So Far

I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable to make my NextJS app recognize the page. I also attempted a similar approach using _app.js. It's worth mentioning that we use TypeScript so the files are saved as .tsx, etc.

This is how my default folder structure looks like -- apparently, we didn't have a root /pages folder at all, contrary to what the documentation recommends. All our application components reside within /src and /src/app.

https://i.stack.imgur.com/v2RKU.png

You can see from the folder structure that I tried:

  • Putting it in
    projectName/src/pages/_document.tsx
  • Trying it in projectName/pages/_document.tsx
  • Experimenting with
    projectName/src/app/pages/_document.tsx
  • Even attempting to place _document.tsx directly in both the projectName/src root and projectName/src/app root.

Unfortunately, none of these attempts seem to work: No matter what I do, my _document.tsx just won't load.

Here's the content of my _document.tsx file, containing the script that should ideally be loaded into the section of the application.

As of now, I have a workaround in place, but I anticipate that my team will request me to utilize _document.tsx. Yet, I'm struggling to have my NextJS app locate it (and never seeing the script or console output this is document talking).

If anyone could shed some light on why I am facing difficulty in getting my _document.tsx to load correctly, and where I might be going wrong, it would be greatly appreciated.

import Document, { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';

class MyDocument extends Document {
  render() {
    console.log("this is document talking");
    return (
      <Html>
        <Head>
          <Script>
            {`window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src="https://cdn.heapanalytics.com/js/heap-"+e+".js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(r,a);for(var n=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["addEventProperties","addUserProperties","clearEventProperties","identify","resetIdentity","removeEventProperty","setEventProperties","track","unsetEventProperty"],o=0;o<p.length;o++)heap[p[o]]=n(p[o])};
  heap.load("123456789");`}
          </Script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

Answer №1

Typically, the priority is given to app/layout.tsx over pages/_document.tsx when both are available for rendering pages in the application. The pages/_document.tsx will handle rendering of pages within the pages directory, so any page added there will be processed by the script in pages/_document.tsx. If you wish to include a script that applies to all documents in both app and pages, it must be included in both app/layout.tsx and pages/_document.tsx.

Here's an example:

// app/layout.tsx
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
      <Script>{`console.log("layout")`}</Script>
    </html>
  );
}

export default Page;

// pages/document.tsx
class MyDocument extends Document {
  render() {
    console.log("this is document talking");
    return (
      <Html>
        <Head>
          <Script strategy="afterInteractive">{`console.log("pages")`}</Script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

// pages/page/1.jsx
import React from "react";
const Page = () => {
  return <div>Page</div>;
};

Upon visiting http://localhost:3000/page/1, https://i.stack.imgur.com/d78Wp.png https://i.stack.imgur.com/XmmgK.png

And on http://localhost:3000/, https://i.stack.imgur.com/8hqxv.png

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

Electron does not have the capability to utilize Google's Speech to Text engine

I am trying to connect my microphone with the Google Speech to Text engine. I came across this page and copied the code into my renderer.ts file, uncommented the lines with const, but when I run it, I encounter an error at line 7 (const client = new speech ...

Using Nestjs to inject providers into new instances of objects created using the "new" keyword

Is it possible to inject a provider into objects created by using the new keyword? For instance: @Injectable() export class SomeService { } export class SomeObject { @Inject() service: SomeService; } let obj = new SomeObject(); When I try this in my t ...

Unable to transfer props object to React component using TypeScript

Apologies if this seems like a basic issue, but I've been struggling with it for the past two days. I'm currently working on writing a simple unit test in Vitest that involves rendering a component to the screen and then using screen.debug(). The ...

Forwarding from server side in NextJS 13

Currently, I am in the process of developing a Next.js 13 application where user authentication is done using Firebase from the server side. Although the authentication process is functional, I am facing an issue with setting up a redirect to the login pag ...

Using NextJs to pass a prop as a className

I'm having difficulty figuring out how to pass a prop to a className, and I'm questioning whether it's even possible. For instance, if the prop category is passed into the function as "category1", can I use styles.category in the ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

Encountering a Typescript error when attempting to access the 'submitter' property on type 'Event' in order to retrieve a value in a |REACT| application

I am facing an issue with my React form that contains two submit buttons which need to hit different endpoints using Axios. When I attempt to retrieve the value of the form submitter (to determine which endpoint to target), I encounter an error while work ...

Tips on extracting value from a pending promise in a mongoose model when using model.findOne()

I am facing an issue: I am unable to resolve a promise when needed. The queries are executed correctly with this code snippet. I am using NestJs for this project and need it to return a user object. Here is what I have tried so far: private async findUserB ...

Refresh default settings for the nextui button

Is it possible to customize the base styles of NextUI components? For example, I would like all NextUI buttons to have a font weight of 600 instead of 400. How can this be achieved? Link to the component: I could manually add: <Button color='pri ...

The inability to destructure the 'store' property from the 'useReduxContext(...)' because of its null value

I am currently using NextJs 13 along with redux toolkit. Whenever I run the npm run build command, I encounter this error: "Cannot destructure property 'store' of 'useReduxContext(...)' as it is null." I suspect that the issue lies wi ...

Angular is failing to show any data on the display, despite there being no apparent errors

As a newcomer to Java and Angular, I am currently enrolled in a course on getting started with Angular. I have been attempting to display information in the navigator, but for some reason, nothing is showing up. Despite thoroughly checking my code, I could ...

How come ngOnChange is unable to detect changes in @Input elements when ngOnDetect is able to do so?

Check out this plunker Please note: In order to see the effect, you need to restart the app after entering the link. import {Component, OnInit, Input, OnChanges, DoCheck} from 'angular2/core' @Component({ selector: 'sub', templat ...

Utilize nextjs-Sourcecode to customize

I have encountered an issue with my next.js application that I believe can be resolved by making a small modification to the next.js source code. To simplify, I have trimmed down the amount of code: export class Head extends Component<HeadProps> { . ...

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...

Encountered an error trying to access '0' property of an undefined object when iterating through data in angular framework

My API is returning data in the format shown below: "fileName": "data.txt", "onlyInFile1": [ { "_id": "60618e87c2077428e4fedde5", "TERMINAL_ID": "Y6152114", "EXTERNAL_STAN": & ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...