Node.js安装branch-sdk时出现ReferenceError: window is not defined报错求助
Hey there! I remember hitting this exact same snag when I was first working with Branch SDK in Node.js—super frustrating when you're just getting started, right? Let me break down what's happening and how to fix it.
Why This Error Happens
The branch-sdk package you installed is built to run in browser environments, where the global window object exists by default. Node.js (whether you're running a backend server or using an SSR framework like Next.js) doesn't have a window object, so the SDK throws that error when it tries to access it.
Solutions Based on Your Use Case
1. If You're Using Branch in a Node.js Backend (Server-Side)
Branch has a dedicated server-side mode for Node.js. You just need to initialize the SDK with your secret key and explicitly tell it to run in server mode:
const Branch = require('branch-sdk'); // Initialize with your Branch secret key and server flag const branch = new Branch('YOUR_BRANCH_SECRET_KEY', { server: true }); // Example: Create a short link using server-side methods branch.createShortUrl( { campaign: 'my-nodejs-campaign', channel: 'email' }, { '$desktop_url': 'https://your-website.com', '$ios_url': 'https://apps.apple.com/your-app' } ).then(link => { console.log('Generated link:', link); }).catch(err => { console.error('Error creating link:', err); });
2. If You're Using Branch in an SSR Framework (e.g., Next.js, Nuxt)
You need to ensure the Branch SDK only loads and runs in the browser/client environment, not during server-side rendering. Here are two reliable approaches:
Option A: Conditional Initialization
Check if window exists before importing/initializing the SDK:
import { useEffect } from 'react'; function MyComponent() { useEffect(() => { // Only run this code in the browser if (typeof window !== 'undefined') { import('branch-sdk').then(({ default: Branch }) => { Branch.init('YOUR_BRANCH_PUBLIC_KEY'); // Add your Branch event tracking or link handling logic here }); } }, []); return <div>Your component content here</div>; } export default MyComponent;
Option B: Dynamic Import with SSR Disabled (Next.js-specific)
Use Next.js's dynamic import to prevent the SDK from loading during server-side rendering:
import dynamic from 'next/dynamic'; import { useEffect } from 'react'; // Dynamically import Branch SDK with SSR disabled const Branch = dynamic(() => import('branch-sdk'), { ssr: false }); function MyComponent() { useEffect(() => { if (Branch) { Branch.init('YOUR_BRANCH_PUBLIC_KEY'); // Use Branch client-side methods here } }, [Branch]); return <div>Your component content here</div>; } export default MyComponent;
Quick Key Check
Don't mix up your keys:
- Server-side: Use your Branch Secret Key (found in your Branch dashboard)
- Client-side: Use your Branch Public Key
内容的提问来源于stack exchange,提问作者Aquafreax

