Перейти к содержимому

Astro Session Driver API

Это содержимое пока не доступно на вашем языке.

Astro sessions allow to share data between requests for on-demand rendered pages. They require an Astro Session Driver to store session data.

Built-in drivers

Astro exports built-in session drivers from astro/config:

import { sessionDrivers } from 'astro/config'

Any unstorage driver can be used, for example:

import { defineConfig, sessionDrivers } from 'astro/config'

export default defineConfig({
    session: {
        driver: sessionDrivers.redis({
            url: process.env.REDIS_URL
        }),
    }
})

:::noteSome drivers may need extra packages to be installed. Some drivers may also require environment variables or credentials to be set. See the Unstorage documentation for more information.:::

Building a session driver

A session driver is made of two parts:

  • The driver config, which lets Astro know what implementation to use at runtime and what config to forward
  • The driver implementation, which handles the storage logic at runtime

The session driver config

A SessionDriverConfig is an object containing a required runtime entrypoint and an optional config. The preferred method for implementing it is to export a function that returns this object and takes the configuration as an optional parameter.

The following example defines a memory driver config:

import type { SessionDriverConfig } from 'astro'

export interface Config {
    max?: number;
}

export function memoryDriver(config: Config = {}): SessionDriverConfig {
    return {
        entrypoint: new URL('./runtime.js', import.meta.url),
        config,
    }
}

It is then registered in the Astro config:

import { defineConfig } from 'astro/config'
import { memoryDriver } from './driver/config'

export default defineConfig({
    session: {
        driver: memoryDriver({
            max: 500
        })
    }
})

entrypoint

Type: string | URL

Добавлено в: astro@6.0.0

Defines the entrypoint for the driver implementation.

config

Type: Record<string, any> | undefined

Добавлено в: astro@6.0.0

Defines the serializable config passed to driver implementation at runtime.

The session driver implementation

A SessionDriver is an object responsible for storing, retrieving and deleting data when using sessions at runtime (e.g. context.session.set()). You can implement it in your session driver module by exporting a default function that takes the driver config as parameter.

The following example implements a memory driver:

import type { SessionDriver } from 'astro'
import type { Config } from './config'
import { LRUCache } from 'lru-cache'

export default function(config: Config): SessionDriver {
    const cache = new LRUCache({ max: config.max })
    return {
        setItem: async (key, value) => {
            cache.set(key, value)
        },
        getItem: async (key) => {
            return cache.get(key)
        },
        removeItem: async (key) => {
            cache.delete(key)
        },
    }
}

setItem()

Type: (key: string, value: any) => Promise<void>

Добавлено в: astro@6.0.0

Defines a function that sets session data by key.

getItem()

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

Добавлено в: astro@6.0.0

Defines a function that retrieves session data by key.

removeItem()

Type: (key: string) => Promise<void>

Добавлено в: astro@6.0.0

Defines a function that removes session data by key.

Unstorage compatibility

Unstorage driver types are compatible with Astro's SessionDriver type.

That means you can use an unstorage package export as an entrypoint. For example:

import type { SessionDriverConfig } from 'astro'

export function configuredRedisDriver(): SessionDriverConfig {
    return {
        entrypoint: 'unstorage/drivers/redis',
        config: {
            tls: true
        }
    }
}

Alternatively, you can import and use an unstorage driver directly in the implementation. For example:

import type { SessionDriver } from 'astro'
import redisDriver from "unstorage/drivers/redis";

export default function(config): SessionDriver {
    return redisDriver({
        ...config,
        tls: true
    })
}
Внести свой вклад Сообщество Поддержать