Skip to content

Be Careful When Concatenating URLs: A Simple Mistake That Causes API Errors

In front-end development, we often dynamically build API URLs based on user data. For example, fetching checkout details based on a shopping cart ID:

const cartId = user.cartId;
const url = `/api/cart/${cartId}/checkout`;

At first glance, this seems completely normal. ✅

But what if the cartId is missing or empty when the request is triggered?

Real Problem: Broken URL Causes Backend Errors

If cartId = '' (an empty string), the final URL becomes:

/api/cart//checkout

Notice the double slashes //? The backend might:

  • Return a 404 Not Found
  • Throw a 500 Internal Server Error
  • Crash or return unexpected behavior

The user ends up facing confusing error messages. ❌

Simple Example: E-commerce Checkout

Imagine an e-commerce site where a user checks out:

function getCheckoutInfo(cartId: string) {
    const url = `/api/cart/${cartId}/checkout`;
    fetch(url)
        .then(res => res.json())
        .then(data => console.log(data));
}

Normal behavior:

getCheckoutInfo('12345');
// Requests /api/cart/12345/checkout

Error case:

getCheckoutInfo('');
// Requests /api/cart//checkout ❌

This leads to server errors and a broken user experience.

How to Prevent It

Add simple validation before building or sending the request:

function getCheckoutInfo(cartId: string) {
    if (!cartId) {
        console.warn('CartId is empty, canceling request.');
        return;
    }
    const url = `/api/cart/${cartId}/checkout`;
    fetch(url)
        .then(res => res.json())
        .then(data => console.log(data));
}

Another option is to validate the URL string itself:

const url = `/api/cart/${cartId}/checkout`;
if (url.includes('//checkout')) {
    console.error('Invalid URL detected:', url);
    return;
}

Key Takeaways

  • Never assume that dynamic values like IDs or keys are ready.
  • Always validate input before building API URLs.
  • An empty string might seem harmless, but it can cause major server-side issues.
  • Prevent invalid API calls early to ensure a better user experience and fewer production bugs.

Comments