DEV Community

nly.kr
nly.kr

Posted on

How to Generate Short URLs with JavaScript and a URL Shortening API

Long URLs are often inconvenient when building web applications.

You may want to:

  • generate short links for social media posts
  • create links for QR codes
  • shorten URLs automatically from an admin dashboard
  • create campaign links programmatically

In this tutorial, we'll use a URL shortening API with both curl and JavaScript's fetch() API.

For the examples, I'll use the API from nly.kr, a URL shortener that I develop and operate.

API endpoint

The endpoint used in this tutorial is:

POST https://nly.kr/api/shorten
Enter fullscreen mode Exit fullscreen mode

The request uses:

Content-Type: application/x-www-form-urlencoded
Enter fullscreen mode Exit fullscreen mode

Authentication is handled with an API key.

The recommended header is:

X-API-Key: your_API_KEY
Enter fullscreen mode Exit fullscreen mode

Bearer authentication is also supported:

Authorization: Bearer your_API_KEY
Enter fullscreen mode Exit fullscreen mode

For JSON responses, send:

Accept: application/json
Enter fullscreen mode Exit fullscreen mode

Required parameters

Two parameters are required when creating a short URL:

Parameter Type Required Description
url String Yes Original HTTP/HTTPS URL
category String Yes Category key for the link

For this example, we'll use:

category=dev
Enter fullscreen mode Exit fullscreen mode

Creating a short URL with curl

The quickest way to test the API is with curl.

curl -X POST "https://nly.kr/api/shorten" \
  -H "X-API-Key: your_API_KEY" \
  -H "Accept: application/json" \
  -d "url=https://example.com" \
  -d "category=dev"
Enter fullscreen mode Exit fullscreen mode

Replace your_API_KEY with your actual API key.

A successful request returns JSON similar to this:

{
  "status": "success",
  "short_url": "https://nly.kr/Ab3XkQ",
  "original_url": "https://example.com",
  "code": "Ab3XkQ",
  "member_idx": 123,
  "category": "dev"
}
Enter fullscreen mode Exit fullscreen mode

For most applications, the value you'll care about is:

short_url
Enter fullscreen mode Exit fullscreen mode

Calling the API with JavaScript

You can make the same request using fetch().

const apiKey = "your_API_KEY";
const longUrl = "https://example.com";
const category = "dev";

fetch("https://nly.kr/api/shorten", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "X-API-Key": apiKey,
    "Accept": "application/json",
  },
  body: new URLSearchParams({
    url: longUrl,
    category,
  }),
})
  .then(async (response) => {
    const data = await response.json().catch(() => null);

    if (!response.ok) {
      throw {
        status: response.status,
        data,
      };
    }

    return data;
  })
  .then((data) => {
    console.log("Short URL:", data.short_url);
  })
  .catch((error) => {
    console.error(
      "Request failed:",
      error.status || "",
      error.data || error
    );
  });
Enter fullscreen mode Exit fullscreen mode

One important detail here is that the API expects:

application/x-www-form-urlencoded
Enter fullscreen mode Exit fullscreen mode

rather than a JSON request body.

That's why we're using URLSearchParams.

Using Bearer authentication

If you prefer the Authorization header, you can use:

curl -X POST "https://nly.kr/api/shorten" \
  -H "Authorization: Bearer your_API_KEY" \
  -H "Accept: application/json" \
  -d "url=https://example.com" \
  -d "category=dev"
Enter fullscreen mode Exit fullscreen mode

For most cases, using the recommended X-API-Key header is simpler.

Handling API errors

If a required parameter is missing, the API returns an error response.

For example:

{
  "status": "error",
  "message": "Category is required."
}
Enter fullscreen mode Exit fullscreen mode

Possible HTTP responses include:

Status Meaning
400 Bad Request
401 Unauthorized
405 Method Not Allowed
500 Server Error

In production code, it's a good idea to check both the HTTP status code and the returned JSON.

Don't expose private API keys in frontend code

The JavaScript example above contains:

const apiKey = "your_API_KEY";
Enter fullscreen mode Exit fullscreen mode

This is useful for demonstrating the request, but private API keys should generally not be embedded directly in frontend JavaScript.

Anything sent to the browser can be inspected by users.

For production applications, consider calling the URL shortening API from your backend instead:

Browser
   ↓
Your server
   ↓
URL shortening API
Enter fullscreen mode Exit fullscreen mode

This lets your server keep the API key private.

Practical use cases

Once you receive short_url, you can use it in many workflows.

For example:

  • store it in your database
  • include it in email campaigns
  • generate QR codes
  • create social media links
  • generate short links automatically from a CMS
  • create campaign-specific tracking links

Conclusion

A URL shortening API makes it easy to automate link generation.

The basic flow is:

  1. receive the original URL
  2. send it to the API
  3. get the short_url
  4. store or share the generated link

API documentation:

https://nly.kr/en/api

If you just want to shorten a URL directly in the browser:

https://nly.kr/en/create-short-url


Disclosure: I develop and operate nly.kr. I used its API here as a practical example for this tutorial.

Top comments (0)