How the duck can I use .p8 to get the Mapkit Server API token to use it without 7 day duration?

https://developer.apple.com/documentation/applemapsserverapi/creating-and-using-tokens-with-maps-server-api

This doesn't really say what to do with .p8 private key. I know I am a noob but I really don't understand Apple Doc at all. There is no example or anything like that.

const appleMapKit = await fetch("https://maps-api.apple.com/v1/token", {
  headers: {
    Authorization: `Bearer ${server_api_token}`,
  },
});

This is what I did but because I created the token on website, server_api_token only lasts 7 days.

So, I tried to use Profile - Key to replace that. I have .p8 file and how can I use this to create the token for the server api?

This is how I did it. I don't know how correct is it but it works for me. Let me know if this helps.

import { AppleMapToken } from "@/types/global";

const APPLE_MAPKIT_JS_TOKEN = process.env.APPLE_MAPKIT_JS_TOKEN!;

async function getToken(): Promise<AppleMapToken> {
  if (global.AppleMapToken && global.AppleMapToken.expiresAt > Date.now()) {
    return global.AppleMapToken;
  }

  const token = await fetchAppleMapsToken();

  return token;
}

async function fetchAppleMapsToken(): Promise<AppleMapToken> {
  const response = await fetch("https://maps-api.apple.com/v1/token", {
    headers: {
      Authorization: `Bearer ${APPLE_MAPKIT_JS_TOKEN}`,
      "Content-Type": "application/json",
    },
  });

  if (!response.ok) {
    throw new Error("Failed to fetch Apple Maps token");
  }

  const data = (await response.json()) as AppleMapToken;
  global.AppleMapToken = {
    accessToken: data.accessToken,
    expiresInSeconds: data.expiresInSeconds,
    expiresAt: Date.now() + data.expiresInSeconds * 1000,
  };

  return global.AppleMapToken;
}

export async function getNearbyPois(lat: string, lng: string) {
  const limit = 5;
  const offset = 0;
  const radius = 10000;
  const mkjsVersion = "5.78.112";

  const url = `https://api.apple-mapkit.com/v1/nearbyPoi?center=${lat}%2C${lng}&radius=${radius}&lang=en&limit=${limit}&offset=${offset}&mkjsVersion=${mkjsVersion}`;
  const token = await getToken();

  try {
    const response = await fetch(url, {
      headers: {
        Authorization: `Bearer ${token.accessToken}`,
        "Content-Type": "application/json",
      },
    });

    if (!response.ok) {
      throw new Error("Failed to fetch POIs from Apple Maps API");
    }

    const data = await response.json();
    return data.results;
  } catch (error) {
    console.error("Error fetching POIs:", error);
    return [];
  }
}
How the duck can I use .p8 to get the Mapkit Server API token to use it without 7 day duration?
 
 
Q