Next.js Discord

Discord Forum

headers() in global-error.tsx

Answered
Kapatid posted this in #help-forum
Open in Discord
Avatar
I saw this file convention and wanted to know if there is a way for me to get headers() so that I can do some conditional rendering.

https://nextjs.org/docs/app/api-reference/file-conventions/error#global-errorjs
Answered by Kapatid
Found another way here is my solution:

"use client"

import { useEffect, useState } from "react"

export default function GlobalError({
  error
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  const [referrer, setReferrer] = useState<string | null>(null)
  const hasStripeErr = referrer?.includes("https://checkout.stripe.com")

  useEffect(() => {
    setReferrer(document.referrer)
    // Client-side error when coming from a hosted Stripe checkout page
    if (document.referrer?.includes("https://checkout.stripe.com"))
      window.location.reload()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <html>
      <body>{!hasStripeErr && <h2>{error.message}</h2>}</body>
    </html>
  )
}
View full answer

3 Replies

Avatar
"use client"

import { headers } from "next/headers"
import Script from "next/script"

export default function GlobalError({
  error
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  const referer = headers().get("referer")

  return (
    <html>
      <body
        className={
          referer?.includes("https://checkout.stripe.com/") ? "text-white" : ""
        }
      >
        {referer?.includes("https://checkout.stripe.com/") && (
          <Script strategy="beforeInteractive" id="stripe-redirect-error">
            {`window.location.reload();`}
          </Script>
        )}

        <h2>{error.message}</h2>
      </body>
    </html>
  )
}


I needed to do this because currently whenever I get redirected from my hosted Stripe checkout I get an Application error/client-side exception message
I know its a client component but is there another way for me to do this?
Avatar
Found another way here is my solution:

"use client"

import { useEffect, useState } from "react"

export default function GlobalError({
  error
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  const [referrer, setReferrer] = useState<string | null>(null)
  const hasStripeErr = referrer?.includes("https://checkout.stripe.com")

  useEffect(() => {
    setReferrer(document.referrer)
    // Client-side error when coming from a hosted Stripe checkout page
    if (document.referrer?.includes("https://checkout.stripe.com"))
      window.location.reload()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <html>
      <body>{!hasStripeErr && <h2>{error.message}</h2>}</body>
    </html>
  )
}
Answer