100

I currently use _document.js to inject css into my Next.js app and I would like to start using _app.js to help inject data into pages.

Was wondering if it possible to use _document and _app in tandem or should we only use one or the other?

cfnerd
  • 3,658
  • 12
  • 32
  • 44
ramesh
  • 2,296
  • 4
  • 19
  • 29
  • 5
    Here is a comparsion betwen _app.js and _document.js https://zeit.co/blog/next6#app-component In short you can use both. – lependu Jun 28 '18 at 13:20

1 Answers1

111

Short answer: Yes, You can use both. They serve different purpose and can be used in the same application.

According to NextJS docs:

Next.js uses the App component to initialize pages.

To override, create the ./pages/_app.js file and override the App class

and

Pages in Next.js skip the definition of the surrounding document's markup. For example, you never include <html>, <body>, etc. To override that default behavior, you must create a file at ./pages/_document.js, where you can extend the Document class.

Note: _document.js is only rendered on the server side and not on the client side. so event handlers like onClick is not going to work.

Just Mohit
  • 141
  • 1
  • 13
MoHo
  • 2,402
  • 1
  • 21
  • 22
  • So _app is only rendered on client side and _document on server side? Does on wraps the other -_document wrapping _app or reverse? thanks for any hint – Webwoman Feb 08 '19 at 17:04
  • 31
    @Webwoman `_app.js` is rendered on both server-side and client-side (on the server during the initial SSR, on the client-side after hydration and then on every page/route navigation). `_document.js` "wraps" `_app.js`. – Borek Bernard Aug 11 '19 at 09:31
  • 1
    Where's the documentation for _app? – wildeyes Jan 11 '20 at 18:20
  • 1
    It would appear `_app.js` is only mentioned in the 'Learn' section here: https://nextjs.org/learn/basics/assets-metadata-css/global-styles Note: you will need to restart your server after adding it. – 1thrasher May 22 '20 at 18:53
  • 3
    hello there is it SAFE to inject env variables into the _document.js html head tag ? thanks –  Jan 15 '21 at 11:37
  • 1
    @mangrove108 it will work, I don't know what you mean by "safe". I wouldn't advise you to inject confidential information there since it will be visible to the client, but why would you want to access `process.env` from `_document.js`? – Aryan Beezadhur Jul 23 '21 at 19:49
  • i am still a bit confused about ssr and env in nextjs. Guess i need to study more –  Jul 24 '21 at 07:09
  • There are valid use cases for exposing env vars, but it's recommended to only use those with the explicit `NEXT_PUBLIC_` prefix, which are meant to be public. Currently using this to output build info for debugging purposes (e.g. build time, git commit hash) – David Calhoun Aug 11 '21 at 21:19
  • documentation for _app can be found here: https://nextjs.org/docs/advanced-features/custom-app – Lelo Jun 03 '22 at 20:31