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

Context

H1

Context is an object that contains information and useful methods related to the current request. Context instances are different between different requests.

Context Content

NamePurposeCondition
context.loggerLogger object used for loggingAlways present
context.executeIdUnique identifier of the current requestAlways present
context.headersHeaders of the current requestAlways present
context.pathPath of the current requestAlways present
context.detail.requestCurrent HTTP request objectOnly present when called via HTTP
context.detail.responseCurrent HTTP response objectOnly present when called via HTTP
context.detail.ipIP address of the current requestOnly present when called via HTTP
context.detail.fullurlReal URL object of the current requestOnly present when called via HTTP

Detail

The content in context.detail is not present in all environments. Typically, this content is only available during HTTP execution. The most common scenario is that this content does not exist during testing and is only present in real HTTP requests.

Extending Context

You can also extend the Context. You can think of it as a “globalThis” shared between requests. For example, you can read user data in middleware and attach it to context.user. Then, in your API, you can directly access the current user’s information through context.user.

Also, don’t forget to edit the /src/context.ts file to add the types for the extended Context! Note that extending the Context type does not mean the data actually exists in the Context. Besides the default properties of Context, you need to write code to attach the data to the Context.

/src/context.ts
import type { MilkioContext } from "milkio";
export type Context = {
// Added user information type
user: {
id: string;
name: string;
email: string;
};
// ...
} & MilkioContext;