Fetch URL with credentials in JavaScript

Let's assume that you have the following URL:

terminal
http://${user}:${pass}@${address}:${port}/set?operation=status

If you want to fetch the URL with credentials, you need to set the headers as Authorization and encode user and pass in base-64.

javascript
const fetchURL = async (user, pass, address, port) => {
    
    // If you try to fetch the URL like
    // let url = `http://${user}:${pass}@${address}:${port}/set?operation=status`;
    // let res = await fetch(url);
    // It won't work, you need to include user and pass in the header

    let url = `http://${address}:${port}/set?operation=status`;

    let res = await fetch(url, {headers: {'Authorization': 'Basic ' +  btoa(user + ":" + pass) }});

    if(res.ok){

        // Do something here

    }

}

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