Skip to content
Urlzee

How to Shorten URLs with JavaScript and Node.js

By Urlzee Team · Published · 6 min read

To shorten a URL from JavaScript, send a POST request with the long URL to a shortener's API and read the short URL from the JSON response. In Node.js 18 or later this takes a single fetch call and no packages. The examples below use the Urlzee API and run as written once your key is set.

What do you need to get started?

Node.js 18 or newer, and an API key.

  1. Check your version with node --version. Version 18 added the built-in fetch used here.
  2. Create a free Urlzee account, open Dashboard → API keys and create a key. It is shown once.
  3. Put the key in an environment variable:
export URLZEE_API_KEY="uz_live_YOUR_KEY"

Save the examples with an .mjs extension, or set "type": "module" in package.json, so that import and top-level await work.

How do you shorten a URL with fetch?

Here is the smallest complete program. Save it as shorten.mjs and run node shorten.mjs.

const res = await fetch("https://urlzee.com/api/v1/links", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.URLZEE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ url: "https://example.com/a/very/long/page" }),
});

const { data, error } = await res.json();
if (!res.ok) throw new Error(error.message);

console.log(data.short_url);

The API replies with 201 Created and a data object containing id, slug, short_url, destination, title, clicks, is_active, expires_at and created_at. On failure there is an error object instead, with a machine-readable code and a human-readable message.

How do you turn that into a reusable function?

Wrap the request once, so every call gets the same headers and the same error handling. This helper is used by the remaining examples; save it as urlzee.mjs.

const API = "https://urlzee.com/api/v1";

export class UrlzeeError extends Error {
  constructor(status, code, message, retryAfter) {
    super(message);
    this.status = status;
    this.code = code;
    this.retryAfter = retryAfter;
  }
}

export async function api(path, { method = "GET", body } = {}) {
  const res = await fetch(`${API}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.URLZEE_API_KEY}`,
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(10_000),
  });

  const json = await res.json().catch(() => null);
  if (!res.ok) {
    throw new UrlzeeError(
      res.status,
      json?.error?.code ?? "http_error",
      json?.error?.message ?? `HTTP ${res.status}`,
      Number(res.headers.get("retry-after")) || null,
    );
  }
  return json;
}

export async function shorten(url, options = {}) {
  const { data } = await api("/links", { method: "POST", body: { url, ...options } });
  return data;
}

Three details are worth copying into any API client:

  • AbortSignal.timeout(10_000) gives up after ten seconds instead of hanging forever.
  • res.json().catch(() => null) copes with a response that is not JSON, such as an error page from a proxy.
  • The thrown error carries status, code and retryAfter, so callers can decide what to do without parsing strings.

Using it:

import { shorten } from "./urlzee.mjs";

const link = await shorten("https://example.com/launch", {
  alias: "launch",
  title: "Launch page",
});
console.log(link.short_url, link.id);

alias sets a custom ending of 3 to 50 letters, numbers, hyphens or underscores. title is a label for your dashboard. A third option, expires_at, takes an ISO 8601 date and needs the Pro or Business plan.

How do you handle errors properly?

Branch on the error's code. The API uses standard status codes, and each has a clear cause.

import { shorten, UrlzeeError } from "./urlzee.mjs";

try {
  const link = await shorten("https://example.com/launch", { alias: "launch" });
  console.log(link.short_url);
} catch (err) {
  if (!(err instanceof UrlzeeError)) throw err; // network failure, timeout

  if (err.code === "alias_taken") {
    console.error("That alias is in use. Pick another.");
  } else if (err.status === 422) {
    console.error(`Rejected: ${err.message}`); // invalid or blocked URL, bad alias
  } else if (err.status === 401) {
    console.error("Check URLZEE_API_KEY.");
  } else if (err.status === 429) {
    console.error(`Rate limited. Retry in ${err.retryAfter} seconds.`);
  } else {
    throw err;
  }
}

A 422 deserves a note. Urlzee validates every destination, and refuses raw IP addresses, private hosts, links to other shorteners and URLs flagged as unsafe. If your application shortens URLs typed by users, pass the message back to them, since it says what was wrong. The full list of codes is in the API documentation.

How do you shorten many URLs without hitting the rate limit?

Work through the list one request at a time, and wait when told to. Firing everything at once with Promise.all is the fastest way to earn a 429.

import { setTimeout as sleep } from "node:timers/promises";
import { shorten, UrlzeeError } from "./urlzee.mjs";

const urls = [
  "https://example.com/products/linen-apron",
  "https://example.com/products/oak-board",
  "https://example.com/products/tea-towel-set",
];

for (const url of urls) {
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const link = await shorten(url);
      console.log(`${url} -> ${link.short_url}`);
      break;
    } catch (err) {
      const retryable = err instanceof UrlzeeError && err.status === 429
        && err.retryAfter !== null && err.retryAfter <= 60;
      if (!retryable || attempt === 3) {
        console.error(`${url} failed: ${err.message}`);
        break;
      }
      await sleep(err.retryAfter * 1000);
    }
  }
}

The retryAfter <= 60 check matters. A 429 can mean two things: you sent too many requests this minute, or you have used your monthly quota. In the second case Retry-After can be hours or days, and a script should stop and report it, not sleep through it.

Per-minute limits are 10 requests on the Free plan, 60 on Pro and 300 on Business. For background on these headers, see API rate limiting explained. If the job is a one-off and you would rather not write code, the bulk URL shortener accepts a pasted list.

Listing is paginated. Request pages until you have collected total items:

import { api } from "./urlzee.mjs";

const links = [];
for (let page = 1; ; page++) {
  const res = await api(`/links?page=${page}&limit=100`);
  links.push(...res.data);
  if (links.length >= res.total || res.data.length === 0) break;
}
console.log(`${links.length} links`);

if (links.length > 0) {
  const stats = await api(`/links/${links[0].id}/stats?days=30`);
  console.log(stats.data);
}

The statistics response contains the click total for the period, clicks per day and the top countries, referrers, devices, browsers and operating systems, with bots counted separately. Remember that each page and each stats call is one request against your quota.

How do you shorten URLs from a web page safely?

Put a small endpoint on your own server between the browser and the API. The browser sends the long URL to your endpoint; your endpoint adds the key and forwards the request. The key never leaves the server.

Here is a dependency-free version using Node's built-in HTTP server:

import { createServer } from "node:http";
import { shorten, UrlzeeError } from "./urlzee.mjs";

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/shorten") {
    res.writeHead(404).end();
    return;
  }
  try {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const { url } = JSON.parse(raw);
    const link = await shorten(url);
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ short_url: link.short_url }));
  } catch (err) {
    const status = err instanceof UrlzeeError ? err.status : 400;
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: err.message }));
  }
}).listen(3000);

From the page, call your own endpoint:

const res = await fetch("/shorten", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://example.com/launch" }),
});
const { short_url } = await res.json();

Before you deploy something like this, protect it. An open /shorten endpoint lets strangers spend your quota and create links under your account. Require your application's own login, limit how often each user can call it, and cap the size of the request body. The reasons the key must stay server-side are set out in API key security best practices.

For the same tasks in another language, see how to shorten URLs with Python. For a tour of every endpoint with curl, including updating and deleting links, see the URL shortener API getting-started guide.

Frequently asked questions

Can I shorten a URL with JavaScript in the browser?
Not directly with an API key, because any key in front-end code is visible to everyone who loads the page. Send the long URL to your own server and let the server call the shortener API with the key.
Do I need an npm package to shorten URLs in Node.js?
No. Node.js 18 and later include a global fetch function, which is all you need to call a REST API such as Urlzee's. The examples in this guide use no dependencies.
How do I shorten many URLs in a loop without hitting rate limits?
Send requests one after another rather than all at once, and when the API answers 429, wait the number of seconds in the Retry-After header before trying that URL again.
Where should I store the API key in a Node.js project?
In an environment variable, read with process.env. Keep any .env file out of version control, and use your hosting platform's secret settings in production.