uber
uber
HHono
Created by uber on 10/21/2024 in #help
Append Authorization access token to RPC client in asynchronous way (amplify auth/cognito)
fixed ✅: Hono client allows us to pass a function for headers that can be async :
const rpcClient = hc<AdminRPC>(process.env.NEXT_PUBLIC_API_URL!, {
headers: async () => ({
Authorization: `Bearer ${await getAccessToken()}`,
}),
});
const rpcClient = hc<AdminRPC>(process.env.NEXT_PUBLIC_API_URL!, {
headers: async () => ({
Authorization: `Bearer ${await getAccessToken()}`,
}),
});
3 replies
HHono
Created by uber on 10/21/2024 in #help
Append Authorization access token to RPC client in asynchronous way (amplify auth/cognito)
Is this terrible? having to create the client in a async way everytime i want to perform a http call.. :
import { AdminRPC } from "@my-sst-monorepo/functions/admins/rpc";
import { fetchAuthSession } from "aws-amplify/auth";
import { hc } from "hono/client";

const getAccessToken = async () => {
const session = await fetchAuthSession();
if (!session.tokens) {
throw new Error("No session");
}
return session.tokens.accessToken.toString();
};

const createRpcClient = async () => {
const accessToken = await getAccessToken();
return hc<AdminRPC>(process.env.NEXT_PUBLIC_API_URL!, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
};

export async function listAdmins() {
const rpc = await createRpcClient();
const res = await rpc.admins.$get();
if (!res.ok) {
throw new Error(`Failed to list admins: ${res.status}`);
}
return await res.json();
}
import { AdminRPC } from "@my-sst-monorepo/functions/admins/rpc";
import { fetchAuthSession } from "aws-amplify/auth";
import { hc } from "hono/client";

const getAccessToken = async () => {
const session = await fetchAuthSession();
if (!session.tokens) {
throw new Error("No session");
}
return session.tokens.accessToken.toString();
};

const createRpcClient = async () => {
const accessToken = await getAccessToken();
return hc<AdminRPC>(process.env.NEXT_PUBLIC_API_URL!, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
};

export async function listAdmins() {
const rpc = await createRpcClient();
const res = await rpc.admins.$get();
if (!res.ok) {
throw new Error(`Failed to list admins: ${res.status}`);
}
return await res.json();
}
3 replies