Lightyear LogoLightyear Docs

Step 8 - Next steps

You've built a working HubSpot integration! Let's explore how to make it production-ready and what else you can build.

Production considerations

1. OAuth flow implementation

Instead of manual authorization, implement the full OAuth flow:

// Example OAuth redirect endpoint
app.get("/oauth/hubspot/callback", async (req, res) => {
  const { code, state } = req.query;
 
  // Exchange code for tokens via Lightyear API
  const response = await lightyearAPI.exchangeOAuthCode({
    app: "hubspot",
    code,
    managedUserId: state.userId,
  });
 
  // Redirect back to your app
  res.redirect("/integrations/success");
});

2. Error handling and retries

Add robust error handling:

async function createCompanyWithRetry(
  accessToken,
  companyName,
  maxRetries = 3,
) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await createCompany(accessToken, companyName);
    } catch (error) {
      if (error.statusCode === 429) {
        // Rate limited
        await sleep(Math.pow(2, i) * 1000); // Exponential backoff
        continue;
      }
      throw error;
    }
  }
}

3. Security best practices

  • Never expose API keys in client-side code
  • Use environment variables or secure key management
  • Implement proper authentication for your endpoints
  • Validate all user input

4. Logging and monitoring

const logger = require("your-logger");
 
async function createCompany(accessToken, companyName) {
  logger.info("Creating company", { companyName, userId });
 
  try {
    const result = await makeRequest(options, data);
    logger.info("Company created successfully", { companyId: result.id });
    return result;
  } catch (error) {
    logger.error("Failed to create company", { error, companyName });
    throw error;
  }
}

Extending the script

Add more operations

// Update a company
async function updateCompany(accessToken, companyId, updates) {
  const options = {
    hostname: "api.hubapi.com",
    path: `/crm/v3/objects/companies/${companyId}`,
    method: "PATCH",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
  };
 
  return await makeRequest(options, { properties: updates });
}
 
// Create a contact
async function createContact(accessToken, contactData) {
  const options = {
    hostname: "api.hubapi.com",
    path: "/crm/v3/objects/contacts",
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
  };
 
  return await makeRequest(options, { properties: contactData });
}

Build a web interface

Instead of a CLI tool, create a web app:

// Express.js example
app.post("/api/companies", authenticateUser, async (req, res) => {
  try {
    const { companyName } = req.body;
    const { userId } = req.user;
 
    // Get access token from Lightyear
    const accessToken = await getAccessTokenForUser(userId);
 
    // Create company
    const company = await createCompany(accessToken, companyName);
 
    res.json({ success: true, company });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Using Lightyear actions

Instead of direct API calls, you can use Lightyear's action system:

// Define an action in your Lightyear project
defineAction({
  name: "createCompany",
  title: "Create Company",
  app: "hubspot",
  input: z.object({
    name: z.string(),
    domain: z.string().optional(),
  }),
  run: async ({ input, auth }) => {
    const response = await auth.post("/crm/v3/objects/companies", {
      properties: input,
    });
    return response.data;
  },
});
 
// Call it from your app
const result = await lightyearAPI.runAction({
  action: "createCompany",
  managedUserId: "hubspot-test-user",
  input: {
    name: "Acme Corporation",
  },
});

Webhook handling

Set up webhooks to receive real-time updates:

// In your Lightyear project
defineWebhook({
  name: "companyUpdated",
  title: "Company Updated",
  app: "hubspot",
  run: async ({ body, headers }) => {
    // Process the webhook
    const { companyId, properties } = body;
 
    // Update your database
    await updateLocalCompany(companyId, properties);
 
    return { success: true };
  },
});

Additional resources

Congratulations!

You've successfully built a HubSpot integration using Lightyear! You've learned how to:

  • Set up and configure integrations
  • Manage user credentials securely
  • Build scripts that interact with third-party APIs
  • Handle authentication and authorization

From here, you can expand this integration to handle more complex workflows, add more services, or build a full-featured application. Happy building!

On this page