JavaScript policy : how to call external API


As part of a custom JS policy, I want to get data from an external API.
For example, I want to know if the weather in my city is good as part of my policy process.
It seems like fetch() is not available within a policy, is there any other way to do this ?
I want this call to be made every time the policy is applied.

An example of policy would be :

async function getWeather(location) {
    let url = 'api-url/${location}/weather.json';
    try {
        let res = await fetch(url);
        return await res.json();
    } catch (error) {

var context = $evaluation.getContext();
var identity = context.getIdentity();
var attributes = identity.getAttributes();
if (attributes.exists('location') === true) {
        var location = attributes.getValue('location').asString(0);
        if (getWeather(location) == "good") {
        } else {

Thank you in advance for your help

I’m not completely sure what your problem is but don’t you need to add a bearer token?

fetch(url, { headers: {
          'Authorization': 'Bearer ' + keycloak.token,

My problem is that fetch cannot be used in KC policies. It just gets ignored !

Can you show an example of that? Is the user logged in what is the value of keycloak.token?

Based on this discussion: [keycloak-dev] Using plain javascript in javascript based policy
and a ticket they linked to, It appears that keycloak does not support standard built-in javascript functions that you would find in a web browser or in nodejs.
Unfortunately the ticket was closed…
Addendum 1:
Based on the newest documentation (today v15.0.0) you can no longer deploy js the same way. It now requires a Java jar file as well. I’m curious if the latest JS engine supports calls to external resources now.
Addendum 2:
It appears that they are still using the Nashorn JS engine in the latest version today. There is a ticket open to get rid of it. This engine does not support any web requests. Here is the ticket: