如何在Node.js后台系统批量生成Branch.io用户专属推荐链接?
Hey there! I've tackled this exact scenario before—moving from single-user referral links in React Native to batch processing in a Node.js backend. Let's break down the steps to make this work smoothly.
Step 1: Install Branch's Node.js SDK
First, you'll need the server-side Branch SDK (not the React Native one) to interact with their API from your backend:
npm install branch-sdk # or yarn add branch-sdk
Step 2: Initialize the Branch Client
You'll need your Branch Server Key (find this in your Branch dashboard under Settings > API Keys). Make sure to use the server key, not the client-side one!
const Branch = require('branch-sdk'); // Load environment variables (use dotenv for better security) require('dotenv').config(); // Initialize Branch client const branch = new Branch(process.env.BRANCH_SERVER_KEY);
Step 3: Fetch All Users from Your Database
First, grab all the users you need to generate links for. I'll use Mongoose (MongoDB) as an example, but adjust this to match your database setup (MySQL, PostgreSQL, etc.):
// Example with Mongoose const User = require('./models/User'); async function getAllUsers() { // Fetch only the fields you need: user ID and email return await User.find({}, '_id email'); }
Step 4: Batch Generate Referral Links
Loop through each user to create their unique referral link. We'll reuse the same pattern as your React Native code, but adapted for Node.js. Important: Add small delays between requests to avoid hitting Branch's rate limits.
async function generateReferralLinks(users) { const userLinkData = []; for (const user of users) { try { // Set the user's identity (matches your React Native code) await branch.setIdentity(user._id.toString()); // Create the Branch Universal Object (match your RN config here!) const branchUniversalObject = await branch.createBranchUniversalObject({ canonicalIdentifier: `user/${user._id}`, title: 'Your App Referral', contentDescription: 'Share this link to invite friends to join!', contentImageUrl: 'https://your-app.com/referral-banner.png', }); // Generate the short referral link with custom properties const { url } = await branchUniversalObject.generateShortUrl({ channel: 'email', feature: 'referral', tags: ['batch-referral'], data: { referrerId: user._id.toString(), // Track who the referrer is }, }); userLinkData.push({ userId: user._id, email: user.email, referralUrl: url, }); // Add a small delay to avoid rate limiting await new Promise(resolve => setTimeout(resolve, 100)); } catch (err) { console.error(`Failed to generate link for user ${user._id}:`, err); // Continue processing other users instead of stopping continue; } } return userLinkData; }
Step 5: Send Emails with Referral Links
Use a library like Nodemailer to send the generated links to each user. First install it:
npm install nodemailer # or yarn add nodemailer
Then set up the email sender and batch send:
const nodemailer = require('nodemailer'); // Configure your email transporter (use your email service credentials) const transporter = nodemailer.createTransport({ service: 'Gmail', // Or Outlook, SendGrid, etc. auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASS, }, }); async function sendReferralEmails(userLinks) { for (const user of userLinks) { try { const mailOptions = { from: 'Your App Team <no-reply@yourapp.com>', to: user.email, subject: 'Your Personal Referral Link is Here!', html: ` <h3>Hi there!</h3> <p>Thanks for being part of our community. Here's your exclusive referral link:</p> <a href="${user.referralUrl}" style="padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 4px;">Share My Referral Link</a> <p>Or copy this URL: ${user.referralUrl}</p> <p>Cheers,<br>The Your App Team</p> `, }; await transporter.sendMail(mailOptions); console.log(`Sent referral email to ${user.email}`); // Add delay to avoid email service rate limits await new Promise(resolve => setTimeout(resolve, 500)); } catch (err) { console.error(`Failed to send email to ${user.email}:`, err); continue; } } }
Step 6: Tie It All Together
Create a main function to run the entire batch process:
async function runBatchReferralProcess() { try { // 1. Fetch all users const users = await getAllUsers(); console.log(`Found ${users.length} users to process`); // 2. Generate referral links const userLinks = await generateReferralLinks(users); console.log(`Successfully generated ${userLinks.length} referral links`); // 3. Send emails await sendReferralEmails(userLinks); console.log('Batch referral process completed successfully!'); } catch (err) { console.error('Batch process failed:', err); } finally { // Close the Branch client connection await branch.close(); } } // Run the process runBatchReferralProcess();
Key Notes to Avoid Headaches
- Rate Limits: Both Branch and email services (like Gmail) have rate limits. The delays added in the code help, but if you have thousands of users, consider splitting into smaller batches (e.g., 50 users at a time).
- Security: Store all sensitive keys (Branch server key, email credentials) in environment variables using
dotenv—never hardcode them in your codebase. - Error Handling: The code includes try/catch blocks per user so one failure doesn't break the entire batch. You might want to log failed users to a file/database to retry later.
- Consistent Configuration: Make sure the
BranchUniversalObjectand link properties match what you use in React Native. This ensures the referral links behave as expected when clicked.
内容的提问来源于stack exchange,提问作者Ma A

