H
Hono2w ago
REIW

Passing types along from Hono to Next

We are exploring using Hono as a BFF for our next.js app, which works well in our monorepo, however the types generated on the Hono server are not being passed over the wire to next.js. Can anyone point me in the right direction of what to explore. hono server which has data typed correctly.
app.get('/:siteSlug/get-products-by-market', async (c) => {
const siteSlug = c.req.param('siteSlug');

const { data, success } = await getProductsByMarket({
siteSlug,
});

if (success) {
return c.json({ data, success });
}
});
app.get('/:siteSlug/get-products-by-market', async (c) => {
const siteSlug = c.req.param('siteSlug');

const { data, success } = await getProductsByMarket({
siteSlug,
});

if (success) {
return c.json({ data, success });
}
});
function to fetch the data
export async function fetchFromBFF<T>({
action,
siteSlug,
}: FetchFromBFF): Promise<T> {
try {
const response = await fetch(
`http://localhost:1234/api/${siteSlug}/${action}`,
);
const result = response.json();
return result as T;
} catch (error) {
console.log(error);
throw Error;
}
}
export async function fetchFromBFF<T>({
action,
siteSlug,
}: FetchFromBFF): Promise<T> {
try {
const response = await fetch(
`http://localhost:1234/api/${siteSlug}/${action}`,
);
const result = response.json();
return result as T;
} catch (error) {
console.log(error);
throw Error;
}
}
consuming the data in next.js with the data coming as untyped (Property 'data' does not exist on type 'unknown'.)
const {
data: productsByMarketData,
success,
} = await fetchFromBFF({
action: 'get-products-by-market',
siteSlug,
});
const {
data: productsByMarketData,
success,
} = await fetchFromBFF({
action: 'get-products-by-market',
siteSlug,
});
3 Replies
ambergristle
ambergristle2w ago
that's just how generics/typescript work you could try using the hono RPC with a custom fetch fn if that's the path you take, be sure to use the generated types rather than export type AppType = typeof app; you can find more info on type generation in historic threads/chats on this server there are some other options, but they get kind of sketchy type-wise another solution would be to add a parser to your fetch fn. then the expected response type would come from the parsing/validation schema that's arguably more type-safe, but has worse dx. of course you could always combine the two approaches
REIW
REIWOP2w ago
Thanks, I will investigate
Arjix
Arjix2w ago
Another nice option is to use Orval to generate client code (and types) based on an openapi schema Assuming you got a fully typed openapi schema

Did you find this page helpful?