Dub.co API Tutorial: Build a Link Shortener in 5 Minutes

Published: (March 11, 2026 at 07:40 AM EDT)
5 min read
Source: Dev.to

Source: Dev.to

Joshua

Every time you share a link in production — whether it’s in an email campaign, Slack integration, or user dashboard — you’re making a choice: do it manually, use a third‑party service, or build it yourself.

For the longest time, developers had one obvious answer: Bitly. It’s been the industry standard since 2008. But if you’ve tried to use Bitly’s API recently, you’ve probably noticed the same thing I did — it now costs $35 / month just to get basic features that modern apps expect: custom domains, decent analytics, and reliable API access.

Meanwhile, Dub.co quietly launched with the same features Bitly charges $35 for… completely free.

I spent a weekend building a link‑shortener integration into my SaaS, and I’ve decided to skip Bitly entirely. Here’s how to do it in 5 minutes.


Before we jump into code, let’s talk numbers. If you’re managing links across your application, you have three options:

FeatureBitlyDub.co
Custom domain$99 / year (separate)Free
API accessFree (limited)Free (unlimited)
AnalyticsBasicAdvanced (geolocation, device, referrer)
QR codesPaid featureFree, with custom branding
Team collaborationPro tier onlyFree
Price per month$35$0

That’s not a minor difference. That’s a complete business‑model shift.


The hardest part of using Dub.co is… there is no hard part.

  1. Go to and sign up.
  2. Create a workspace.
  3. Get your API key from Settings → API Keys.

You’re done. You now have:

  • A free custom domain (or bring your own)
  • API access
  • A dashboard with real‑time analytics
  • QR‑code generation with your branding

Let’s say you’re building an email‑campaign feature and need to track which links users click. Here’s how to add Dub.co link‑shortening to your backend in under 50 lines.

// Simple Node.js example with Dub API
const axios = require('axios');

async function createShortLink(longUrl, campaignName) {
  try {
    const response = await axios.post(
      'https://api.dub.co/links',
      {
        url: longUrl,
        domain: 'your-domain.com', // Your custom domain
        key: campaignName,          // Custom slug (optional)
        expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
        tags: ['campaign', 'email'],
      },
      {
        headers: {
          Authorization: `Bearer ${process.env.DUB_API_KEY}`,
          'Content-Type': 'application/json',
        },
      }
    );

    return response.data;
  } catch (error) {
    console.error(
      'Failed to create short link:',
      error.response?.data || error.message
    );
    throw error;
  }
}

// Usage
(async () => {
  const shortLink = await createShortLink(
    'https://example.com/ultra-long-product-page-that-nobody-wants-to-share',
    'Q1-2026-campaign'
  );

  console.log(`Short link: ${shortLink.shortUrl}`);
  console.log(`QR Code: ${shortLink.qrCode}`);
})();

Fetching analytics

async function getLinkAnalytics(shortUrl) {
  try {
    const response = await axios.get(
      `https://api.dub.co/links/info?url=${shortUrl}`,
      {
        headers: {
          Authorization: `Bearer ${process.env.DUB_API_KEY}`,
        },
      }
    );

    return response.data;
  } catch (error) {
    console.error(
      'Failed to fetch analytics:',
      error.response?.data || error.message
    );
    throw error;
  }
}

// Usage
(async () => {
  const analytics = await getLinkAnalytics('your-domain.com/Q1-2026-campaign');
  console.log(`Clicks: ${analytics.clicks}`);
  console.log(`Countries: ${JSON.stringify(analytics.countries)}`);
  console.log(`Devices: ${JSON.stringify(analytics.devices)}`);
})();

Generating a branded QR code

async function generateBrandedQR(shortUrl, brandColor) {
  // Returns a PNG URL you can embed directly
  return `https://api.dub.co/qr?url=${shortUrl}&color=${brandColor}`;
}

// Example
(async () => {
  const qrImage = await generateBrandedQR(
    'your-domain.com/Q1-2026-campaign',
    '3B82F6'
  );
  // Use `qrImage` in emails, PDFs, or your app
})();

Real‑World Use Case: Email Campaign Tracking

Here’s how a full email‑campaign system might look:

async function sendCampaignEmail(userEmail, productUrl, campaignId) {
  // 1️⃣ Create a short, trackable link
  const shortLink = await createShortLink(
    productUrl,
    `campaign-${campaignId}`
  );

  // 2️⃣ Generate a branded QR code
  const qrCode = await generateBrandedQR(shortLink.shortUrl, '3B82F6');

  // 3️⃣ Send email with both
  await sendEmail({
    to: userEmail,
    subject: 'Check out our latest product',
    html: `
      
We've got something new for you:

      [Click here](${shortLink.shortUrl})
      

      
Or scan this QR code:

      [Image: QR Code]
    `,
  });

  // 4️⃣ Later, check how many people actually clicked
  const analytics = await getLinkAnalytics(shortLink.shortUrl);
  console.log(`Campaign ${campaignId} clicks: ${analytics.clicks}`);
}

That’s it—five minutes to a fully‑featured, free link‑shortening solution that beats Bitly on price, features, and developer experience. Happy coding!

// Example: Get analytics for a short link
const analytics = await dub.getLinkAnalytics(shortLink.shortUrl);
console.log(`This link has been clicked ${analytics.clicks} times`);

Why Dub.co Wins (Especially for Developers)

  • Open Source — The SDK is open‑source. No vendor lock‑in. You can even self‑host if you want.
  • Developer‑First API — Dub.co was built by developers, for developers. The API is clean, the documentation is complete, and error messages are actually helpful.
  • No Hidden Costs — You get unlimited API calls on the free plan. Bitly charges $35 / month and still rate‑limits you.
  • Custom Branding — Your QR codes can have your logo and brand colors. This actually matters for professional communications.
  • Real Analytics — Not just click counts. You get geolocation data, device info, referrer sources, and more.
  • Team Collaboration — Built‑in team features mean your marketing team can manage links without touching code.

One More Thing: Custom Domains

If you want your links to use your own domain (e.g., go.yourcompany.com instead of dub.co/...), just add it in the Dub.co dashboard and point your DNS records there. It takes 5 minutes, and now every link looks like it’s from your brand.


Get Started Now

If you’re building any kind of link management, affiliate tracking, email campaigns, or QR‑code features, you’re essentially paying Bitly $35 / month for something that Dub.co gives you free.

  • The setup takes literally 2 minutes.
  • The API integration takes 10 minutes.

The payoff? You’ve got professional link management, analytics, and team collaboration built into your product without writing a single line of infrastructure code.

Sign up for free here and start creating short links with your own domain in the next 5 minutes.

0 views
Back to Blog

Related posts

Read more »

Intro About Java Script

Introduction In today’s class I learned a short introduction to JavaScript, so I’ll share some facts about JavaScript in this blog. What Is JavaScript? JavaScr...