Skip to content
当前有符合你浏览器所设置语言的版本,是否前往zh-CN版本的网站?
There is a version suitable for your browser's language settings. Would you like to go to the zh-CN language of the site?
HomeDocument

Metadata

H1

In the Middleware section, we wrote a middleware to ensure user authentication. However, not all APIs need to use it. We can make the middleware aware of which APIs don’t require its protection by setting the meta option in the interface.

The definition of the Meta type is located in the /src/meta.ts file, and you can freely extend it as needed. First, we need to inform the middleware within the API that we allow access for users who are not logged in.

Therefore, we add an allowWithoutLogin option.

/src/meta.ts
export type Meta = {
allowWithoutLogin?: boolean;
};

Now we can set this value in the meta field within the API.

/src/app/your-example/api.ts
export const api = defineApi({
meta: {
allowWithoutLogin: true,
},
action(params: undefined, context) {
return `Hello, world!`;
},
});

Moving on to the middleware, using the useMeta function, we can access the meta option of any API. Now, by checking the allowWithoutLogin option, we can determine whether to allow access to this API for users who are not logged in. If the API doesn’t have this option or it’s set to false, we consider that the API requires our protection; otherwise, we don’t do anything extra.

/src/middlewares/ensure-logined-middleware.ts
export const ensureLoginedMiddleware = defineMiddleware({
beforeExecute: async (context) => {
const meta = await useMeta(context.path);
if (meta.allowWithoutLogin === undefined || !meta.allowWithoutLogin) {
const token = context.headers.get("Authorization");
if (token !== "xxxx-xxxx-xxxx-xxxx") throw reject("DEVICE_NOT_LOGIN", "This device is not logged in yet.");
}
},
});