Skip to content

实验会话

类型:SessionConfig
默认:undefined

¥Type: SessionConfig
Default: undefined

Added in: astro@5.1.0

会话用于在 按需呈现的页面 请求之间存储用户状态。

¥Sessions are used to store user state between requests for on-demand rendered pages.

此实验性功能允许你存储和访问登录状态、购物车内容或其他用户特定数据等项目:

¥This experimental feature allows you to store and access items such as login status, shopping cart contents, or other user-specific data:

src/components/CartButton.astro
---
export const prerender = false; // Not needed in 'server' mode
const cart = await Astro.session.get('cart');
---
<a href="/checkout">🛒 {cart?.length ?? 0} items</a>

会话依赖 可配置会话 driver 将数据存储在 session 对象上。会话 cookie 存储识别会话 ID。

¥Sessions rely on a configurable session driver to store data on the session object. A session cookie stores an identifying session ID.

session 对象 允许你与存储的用户状态(例如,将商品添加到购物车)和会话 ID(例如,在注销时删除会话 ID cookie)进行交互。

¥The session object allows you to interact with the stored user state (e.g. add items to a shopping cart) and the session ID (e.g. delete the session ID cookie when logging out).

¥Enabling experimental sessions

experimental.sessions 的早期版本中,Astro 的官方服务器适配器尚未更新以提供基于平台默认存储功能的默认会话驱动程序。在内置这些 API 之前,除了 添加适配器 之外,你还必须在 experimental.sessions 配置对象中自行指定 driver

¥In this early release of experimental.sessions, Astro’s official server adapters have not yet been updated to provide a default session driver based on the platform’s default storage feature. Until these are built in, you will have to specify a driver yourself in the experimental.sessions configuration object in addition to adding an adapter.

以下部分显示了每个适配器的推荐驱动程序。(此功能的稳定版本将自动为你配置这些。)或者,你可以指定 来自 unstorage 的任何受支持的驱动程序

¥The following sections show the recommended drivers for each adapter. (These will be automatically configured for you in the stable release of this feature.) Alternatively, you can specify any supported driver from unstorage.

使用 Node 适配器配置会话

标题部分 使用 Node 适配器配置会话

¥Configuring sessions with the Node adapter

Node 适配器与 文件系统驱动程序 兼容。请注意,这不能在无服务器环境中使用,因为它们没有共享文件系统。

¥The Node adapter is compatible with the the filesystem driver. Note that this cannot be used in serverless environments as they have no shared filesystem.

astro.config.mjs
{
adapter: node({ mode: 'standalone' }),
experimental: {
session: {
// Required: the name of the unstorage driver
driver: "fs",
},
},
}

为其他适配器配置会话驱动程序

标题部分 为其他适配器配置会话驱动程序

¥Configuring a session driver for other adapters

选择与你的托管平台提供的存储功能相对应的 unstorage driver 名称,例如 Netlify Blobs 驱动程序 (netlify-blobs)Cloudflare KV 驱动程序 (cloudflare-kv-binding)Deno KV 驱动程序 (deno-kv)。你还可以使用跨平台驱动程序,例如 UpstashRedis

¥Choose the unstorage driver name that corresponds to the storage feature provided by your hosting platform, such as the Netlify Blobs driver (netlify-blobs), the Cloudflare KV driver (cloudflare-kv-binding) or the Deno KV driver (deno-kv). You can also use a cross-platform driver such as Upstash or Redis.

¥Driver options

你还可以在单​​独的 session.options 对象中将任何可用选项传递给 unstorage 驱动程序。以下示例配置了 Netlify Blobs 驱动程序,同时还提供了 name 并指定了 consistency 模式:

¥You can also pass any available options to the unstorage driver in a separate session.options object. The following example configures the Netlify Blobs driver while also providing a name and specifying a consistency mode:

astro.config.mjs
{
adapter: netlify(),
experimental: {
session: {
// The name of the unstorage driver is kebab-case
driver: "netlify-blobs",
options: {
name: 'astro-sessions',
// Sessions need strong consistency
consistency: 'strong',
}
},
},
}

¥Using sessions

配置驱动程序后,你可以使用 session 对象与会话进行交互。此对象可在 Astro 组件和页面中作为 Astro.session 访问,也可在 API 端点、中间件和操作中的 context 对象上访问。API 在所有情况下都是相同的。

¥Once you have configured a driver, you can use the session object to interact with the session. This object is accessible as Astro.session in your Astro components and pages and on the context object in API endpoints, middleware and actions. The API is the same in all cases.

在大多数情况下,你只需要使用 Astro.session.get()Astro.session.set()。有关其他可用方法,请参阅 API 部分

¥In most cases you will only need to use Astro.session.get() and Astro.session.set(). For other available methods, see the API section.

¥Astro components and pages

.astro 组件和页面中,你可以通过全局 Astro 对象访问会话对象。例如,要显示购物车中的商品数量:

¥In .astro components and pages, you can access the session object via the global Astro object. For example, to display the number of items in a shopping cart:

src/components/CartButton.astro
---
export const prerender = false; // Not needed in 'server' mode
const cart = await Astro.session.get('cart');
---
<a href="/checkout">🛒 {cart?.length ?? 0} items</a>

¥API endpoints

在 API 端点中,会话对象在 context 对象上可用。例如,要将商品添加到购物车:

¥In API endpoints, the session object is available on the context object. For example, to add an item to a shopping cart:

src/pages/api/addToCart.ts
import type { APIContext } from "astro";
export async function POST(req: Request, context: APIContext) {
const cart = await context.session.get("cart");
cart.push(req.body.item);
await context.session.set("cart", cart);
return Response.json(cart);
}

¥Actions

在操作中,会话对象在 context 对象上可用。例如,要将商品添加到购物车:

¥In actions, the session object is available on the context object. For example, to add an item to a shopping cart:

src/actions/addToCart.ts
import { defineAction } from "astro:actions";
import { z } from "astro:schema";
export const server = {
addToCart: defineAction({
input: z.object({ productId: z.string() }),
handler: async (input, context) => {
const cart = await context.session.get("cart");
cart.push(input.productId);
await context.session.set("cart", cart);
return cart;
},
}),
};

¥Middleware

在中间件中,会话对象在 context 对象上可用。例如,要在会话中设置上次访问时间:

¥In middleware, the session object is available on the context object. For example, to set the last visit time in the session:

src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => {
context.session.set('lastVisit', new Date());
return next();
});

首次访问时会生成会话,并在响应中设置会话 ID cookie。cookie 中不存储任何实际用户数据 - 仅存储用于识别用户会话的 ID。可以使用 Astro.session.regenerate() 随时重新生成会话,并使用 Astro.session.destroy() 销毁会话。

¥Sessions are generated when first accessed, and a session ID cookie is set in the response. No actual user data is stored in the cookie – just an ID that is used to identify a user’s session. The session can be regenerated at any time with Astro.session.regenerate(), and destroyed with Astro.session.destroy().

类型:string | object
默认值:undefined

¥Type: string | object
Default: undefined

用于设置 cookie 选项的可选属性。cookie.name 属性可以通过提供字符串自动设置。要配置其他选项,请提供一个对象。

¥An optional property to set cookie options. The cookie.name property can be automatically set by providing a string. To configure additional options, provide an object.

astro.config.mjs
{
experimental: {
session: {
// If set to a string, this will be used as the cookie name
// cookie: "my-session-id",
// If set to an object, this will allow advanced options to be set
cookie: {
name: "my-session-id"
sameSite: "Strict",
},
}
}
}

¥Sessions API

会话对象在所有 Astro 上下文中都可用,包括组件、操作和 API 端点。在组件中,它通过全局 Astro 对象访问,在操作和 API 端点中,它可在 context 对象上获得。API 在所有情况下都是相同的。

¥The session object is available in all Astro contexts, including components, actions, and API endpoints. In components, it is accessed via the global Astro object, and in actions and API endpoints it is available on the context object. The API is the same in all cases.

使用 devalue 对值进行序列化和反序列化,这是内容层和操作使用的相同库。这意味着支持的类型是相同的,包括字符串、数字、DateMapSetURL、数组和纯对象。

¥Values are serialized and deserialized using devalue, which is the same library used by content layer and actions. This means that supported types are the same, and include strings, numbers, Date, Map, Set, URL, arrays and plain objects.

类型:(key: string) => Promise<any>

¥Type: (key: string) => Promise<any>

返回会话中给定键的值。如果密钥不存在,则返回 undefined

¥Returns the value of the given key in the session. If the key does not exist, it returns undefined.

类型:(key: string, value: any, options?: { ttl: number }) => void

¥Type: (key: string, value: any, options?: { ttl: number }) => void

设置会话中给定键的值。该值可以是任何可序列化的类型。

¥Sets the value of the given key in the session. The value can be any serializable type.

类型:() => void

¥Type: () => void

重新生成会话 ID。最佳做法是在用户登录或提升其权限时调用此方法,以防止会话固定攻击。

¥Regenerates the session ID. Best practice is to call this when a user logs in or escalates their privileges, to prevent session fixation attacks.

类型:() => void

¥Type: () => void

销毁会话,从后端删除 cookie 和对象。当用户注销或其会话无效时,应调用此方法。

¥Destroys the session, deleting the cookie and the object from the backend. This should be called when a user logs out or their session is otherwise invalidated.

¥Further reading

有关完整详细信息和对此实验性 API 提供反馈,请参阅 会话 RFC

¥For full details and to give feedback on this experimental API, see the Sessions RFC.

Astro 中文网 - 粤ICP备13048890号