web-branch-deep-linking-attribution icon indicating copy to clipboard operation
web-branch-deep-linking-attribution copied to clipboard

window is not defined in Next.js

Open Dnguye92 opened this issue 4 years ago • 1 comments

Trying to integrate the web sdk into a nextjs app but the snippet from the docs already throws syntax errors. image

I've also tried integrating with the npm package but when I try to init then I get a window is not defined error even though I'm initializing in a useEffect hook. Any clues as to what's happening? image

Dnguye92 avatar Mar 22 '21 18:03 Dnguye92

I think the trick is to import the SDK dynamically, as explained in https://nextjs.org/docs/advanced-features/dynamic-import.

I'm doing something along these lines:

useEffect(() => {
  async function initAndFetch() {
    const BranchSDK = (await import('branch-sdk')).default

    BranchSDK.init(process.env.NEXT_PUBLIC_BRANCH_KEY!)

    BranchSDK.data(function (err, data) {
      if (err) {
        console.warn(`Branch failed to resolve link: ${err}`)
        return
      }

      // do something with `data`?
    })
  }

  initAndFetch()
}, [])

schonfeld avatar Mar 24 '21 18:03 schonfeld