Skip to content

Instantly share code, notes, and snippets.

@hchocobar
Created May 15, 2026 21:49
Show Gist options
  • Select an option

  • Save hchocobar/89d8d84f74cd47d0191858fe31c6c2b7 to your computer and use it in GitHub Desktop.

Select an option

Save hchocobar/89d8d84f74cd47d0191858fe31c6c2b7 to your computer and use it in GitHub Desktop.
JavaScript: Authentication with Bearer Token

Archivo .env

API_SECRET_KEY=j4oy8uWFCdF18asdfueWER

Arhcivo de JavaScript

export const requestWithAuthentication = async () => {
  // Creo la url ficticia de un recurso protegido
  let url = `https://webHost.com/api/protected`  

  // Leo el valor de la API_KEY que guardé en el archivo .env
  let apiKey = import.meta.env.API_SECRET_KEY
  
  // Creo un objeto denominado 'options' en el cual defino la Autenticación, agregando la API_Key
  let options = {
    headers: {
      Authorization: `Bearer ${apiKey}`
    }
  }
  
  // Ejecuto el fetch() con la url y opciones definidas previamente
  const response = await fetch(url, options);  
  
  // Valido el resultado de la petición
  if (!response.ok) {
    console.log('Error', response.status, response.statusText)
    return false
  }
  
  // Extraigo los datos JSON de la petición
  const data = await response.json()
  
  // Retorno los datos obtenidos
  return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment