UNPKG

@auth0/nextjs-auth0

Version:
34 lines (33 loc) 1.42 kB
import { AccessTokenError } from "../../errors/index.js"; import { normalizeWithBasePath } from "../../utils/pathUtils.js"; export async function getAccessToken(options = {}) { const urlParams = new URLSearchParams(); // We only want to add the audience if it's explicitly provided if (options.audience) { urlParams.append("audience", options.audience); } // We only want to add the scope if it's explicitly provided if (options.scope) { urlParams.append("scope", options.scope); } let url = normalizeWithBasePath(process.env.NEXT_PUBLIC_ACCESS_TOKEN_ROUTE || "/auth/access-token"); // Only append the query string if we have any url parameters to add if (urlParams.size > 0) { url = url + `?${urlParams.toString()}`; } const tokenRes = await fetch(url); if (!tokenRes.ok) { // try to parse it as JSON and throw the error from the API // otherwise, throw a generic error let accessTokenError; try { accessTokenError = await tokenRes.json(); } catch (e) { throw new Error("An unexpected error occurred while trying to fetch the access token."); } throw new AccessTokenError(accessTokenError.error.code, accessTokenError.error.message); } const tokenSet = await tokenRes.json(); return options.includeFullResponse ? tokenSet : tokenSet.token; }