Modern.js uses Hono.js as the BFF and Server runtime framework, so you can extend BFF Server based on the Hono.js ecosystem.
Sometimes in BFF functions, it's necessary to obtain the request context to handle more logic. In such cases, you can use useHonoContext to get it:
import { useHonoContext } from '@modern-js/plugin-bff/server';
export const get = async () => {
const c = useHonoContext();
console.info(`access url: ${c.req.url}`);
return 'Hello Modern.js';
};For more details, refer to useHonoContext.
When using Hono as the runtime framework, you can define interfaces through BFF Functions:
import { Api, Get, Query } from '@modern-js/plugin-bff/server';
import { z } from 'zod';
const QuerySchema = z.object({
id: z.string(),
});
export const getUser = Api(
Get('/user'),
Query(QuerySchema),
async ({ query }) => {
return {
id: query.id,
name: 'Modern.js',
email: 'modernjs@bytedance.com',
};
},
);Hono supports a rich middleware ecosystem, and you can use middleware in BFF functions:
import { Api, Get, Middleware } from '@modern-js/plugin-bff/server';
export const getUser = Api(
Get('/user'),
Middleware(async (c, next) => {
// You can access Hono's Context in middleware
c.res.headers.set('X-Powered-By', 'Modern.js');
await next();
}),
async () => {
return {
name: 'Modern.js',
email: 'modernjs@bytedance.com',
};
},
);For more detailed information about Hono, please refer to the Hono official documentation.