How to create Firebase Dynamic Links using the fetch function in JavaScript

Firebase allows to create short links (Firebase Dynamic Links). It can be done manually, or fetching the API:

jsx
const shortenURL = async (longURL) => {

    // You need to change the API Key by the one provided in the FIrebase Console
    let url = 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[YOUR_API_KEY]';

    // Long dynamic link is composed by 
    // 1. Short URL (by default, Firebase allows you to create https://[YOUR_PROJECT].page.link type of links)
    // 2. Long URL encoded (important to encode the URL, otherwise, Firebase will return a 400 error)
    let longDynamicLink = 'https://[YOUR_PROJECT].page.link/?link=' + encodeURIComponent(longURL);

    let response = await fetch(url, {
      "method": "POST",
      "headers": {
        "content-type": "application/json"
      },
      "body": JSON.stringify( {"longDynamicLink": longDynamicLink} )
    });

    let data = await response.json();

    // Firebase returns a 'shortLink' field with the short URL
    return data.shortLink;

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.