Back to Insights

How to Shorten URLs Programmatically with Node.js and the LinkZip API

How to Shorten URLs Programmatically with Node.js and the LinkZip API

In modern web development, automation is key to scaling your operations. A common requirements is the ability to generate short URLs dynamically. Whether you are building an e-commerce platform that sends SMS tracking codes, a social media tool that publishes automated posts, or an internal notification system, integrating a robust link shortener API is essential.

In this hands-on tutorial, you will learn how to integrate LinkZip.uk into a Node.js backend. We will cover setting up a REST request, sending the appropriate parameters, handling responses, and managing errors.


1. Prerequisites

Before we start writing code, make sure you have the following ready:

  • Node.js installed: Version 18 or higher is recommended (to leverage native fetch without external HTTP clients).
  • A LinkZip account: Sign up for free at LinkZip.uk.
  • An API Key: Generate your key from your user profile settings dashboard. This key acts as your credential to authorize API requests.

2. Setting Up Your Node.js Project

First, create a new directory for your project and initialize a package.json file:

mkdir linkzip-api-demo
cd linkzip-api-demo
npm init -y

Since we are writing modern ES Module code, add "type": "module" to your package.json file. This lets you use import statements instead of require.

{
  "name": "linkzip-api-demo",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "dependencies": {}
}

3. Writing the URL Shortener Script

Create an index.js file in the root of your project. We will write an asynchronous function shortenUrl to consume the LinkZip shortening endpoint.

/**
 * Shortens a long URL using the LinkZip.uk REST API.
 * @param {string} longUrl - The original long URL to shorten.
 * @param {string} customAlias - Optional. Custom alias for the shortened URL.
 * @returns {Promise<string>} The generated short URL.
 */
async function shortenUrl(longUrl, customAlias = '') {
  const API_KEY = 'your_api_key_here'; // Replace with your actual LinkZip API key
  const API_URL = 'https://linkzip.uk/api/shorten';

  const bodyData = {
    url: longUrl,
  };

  if (customAlias) {
    bodyData.alias = customAlias;
  }

  try {
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify(bodyData)
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API Error: ${errorData.message || response.statusText}`);
    }

    const data = await response.json();
    return data.shortUrl; // Returns the generated short URL string
  } catch (error) {
    console.error('Failed to shorten URL:', error.message);
    throw error;
  }
}

// Example usage:
async function run() {
  const targetUrl = 'https://yourwebsite.com/blog/articles/web-development-node-astro';
  const desiredAlias = 'node-astro-tutorial';

  try {
    console.log('Sending request to LinkZip API...');
    const shortUrl = await shortenUrl(targetUrl, desiredAlias);
    console.log('\nSuccess!');
    console.log('Original:', targetUrl);
    console.log('Short URL:', shortUrl);
  } catch (err) {
    console.log('Operation failed.');
  }
}

run();

4. Code Breakdown and Best Practices

A. Authorization Headers

The LinkZip API requires standard Bearer Token authentication in the HTTP headers:

'Authorization': `Bearer ${API_KEY}`

This links the request to your user account and counts toward your plan’s API limits.

B. Handling Custom Aliases

The request body accepts an optional alias parameter. If you supply this, the API attempts to register the URL under that slug (e.g., linkzip.uk/alias). If the alias is already taken by another link, the API returns an error status (typically 409 Conflict), which triggers our script’s catch block.

C. Production Best Practices

  • Environment Variables: Do not hardcode your API key. Use packages like dotenv to store secret credentials in a .env file, keeping them out of your Git repository.
  • Rate Limits and Retries: LinkZip uses rate limits to protect server integrity. If your application sends thousands of links, implement a retry mechanism with exponential backoff to handle temporary 429 Too Many Requests responses.

5. Frequently Asked Questions (FAQ)

What are the API rate limits?

Rate limits vary depending on your account tier. Check your user dashboard on LinkZip.uk to view your current requests-per-minute quota.

Yes, the LinkZip REST API supports PUT or PATCH requests, allowing you to dynamically update the destination target of a short link without changing the public short URL itself.

How do I retrieve click statistics programmatically?

While the /api/shorten endpoint handles link creation, you can fetch analytics and click metrics by sending a GET request to the analytics endpoint /api/analytics/{alias}.


Conclusion

Automating link shortening in Node.js is simple. By consuming the LinkZip.uk REST API, you can easily build dynamic link tracking into your application’s notifications, workflows, and marketing funnels. Implement this code in your next project to take full control of your outbound web traffic.