xavierbriole / react-cookienotice

A lightweight & customizable cookie banner for your React App
https://react-cookienotice.vercel.app
18 stars 5 forks source link

Cannot build Next.js app because "document is not defined in react-cookienotice.es.js" #189

Closed simonlopezwork closed 1 year ago

simonlopezwork commented 1 year ago

Hi Xavier,

Awesome notice first and foremost!

My app was not building in production so I spinned out a fresh non-TS Next.js app. On development, these errors show up in the console/terminal:

image

These errors are present in the fresh next install and in the main app.

When building, these errors show up on multiple pages and Nextjs fails to build.

image

Would like to know your thoughts on the fix. Thanks!

xavierbriole commented 1 year ago

Hello! Thank you for the report, I will take a look on it. To test on my side, i just need to create an empty Next.js app? Nothing more?

simonlopezwork commented 1 year ago

Yes, I think so because they have the same error.

I forgot to mention that I wrapped the CookieNotice component in a Nextjs client component via the "use client" directive.

Thanks again!

On Wed, Aug 16, 2023, 11:41 AM Xavier Briole @.***> wrote:

Hello! Thank you for the report, I will take a look on it. To test on my side, i just need to create an empty Next.js app? Nothing more?

— Reply to this email directly, view it on GitHub https://github.com/xavierbriole/react-cookienotice/issues/189#issuecomment-1679912783, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMSTDIJWH4TF3PFIJL5AJSLXVQ6OXANCNFSM6AAAAAA3R4XGTU . You are receiving this because you authored the thread.Message ID: @.***>

xavierbriole commented 1 year ago

Ok I reproduced. Will try to find a fix.

xavierbriole commented 1 year ago

For SSR you need to import dynamically the module with next/dynamic using { ssr: false }. This prevents the component from being included on the server, and dynamically loads it on the client-side only.

Create a new file which include the CookieNotice component :

import { CookieNotice } from 'react-cookienotice'
import 'react-cookienotice/dist/style.css'

export default function CookieBanner() {
  return <CookieNotice />
}

then you can import it wherever the component is used :

import dynamic from 'next/dynamic'

const CookieBanner = dynamic(
  () => import('./cookie-banner'),
  { ssr: false }
)

export default function Home() {
  return <CookieBanner />
}

This should be working now. Tell me if you need anything else, I'll add it in the README asap.

simonlopezwork commented 1 year ago

Successfullly deployed the app. Thank you very much for being so prompt!