Session
Session(会话)是指在客户端和服务器之间建立的一种持久化的连接。在 Web 应用程序中,Session 通常用来保存用户的登录状态或其他需要跨越多个页面持久化的数据。
在一个 Web 应用程序中,当用户通过浏览器访问网站时,服务器会为该用户创建一个唯一的 Session ID,并将该 ID 记录在用户的浏览器中的 Cookie 中。之后,用户在浏览网站的过程中,服务器将会针对该 Session ID 保存一些数据,比如用户的登录信息、购物车内容等等。
在每次用户向服务器发送请求时,浏览器都会自动将该用户的 Session ID 添加到请求头中,以告诉服务器该请求来自哪个用户的会话。服务器可以根据该 Session ID 来获取该用户保存在 Session 中的信息,并进行对应的处理。
Session 可以通过多种方式来实现,比如使用内存、Redis、数据库等。一般来说,使用 Redis 或数据库来存储 Session 更加可靠和安全。
getSession
ts
export async function getSession<T extends SessionDataT = SessionDataT>(
event: H3Event,
config: SessionConfig,
): Promise<Session<T>> {
const sessionName = config.name || DEFAULT_NAME
// Return existing session if available
if (!event.context.sessions)
event.context.sessions = Object.create(null)
if (event.context.sessions![sessionName])
return event.context.sessions![sessionName] as Session<T>
// Prepare an empty session object and store in context
const session: Session<T> = {
id: '',
createdAt: 0,
data: Object.create(null),
}
event.context.sessions![sessionName] = session
// Try to load session
let sealedSession: string | undefined
// Try header first
if (config.sessionHeader !== false) {
const headerName
= typeof config.sessionHeader === 'string'
? config.sessionHeader.toLowerCase()
: `x-${sessionName.toLowerCase()}-session`
const headerValue = event.node.req.headers[headerName]
if (typeof headerValue === 'string')
sealedSession = headerValue
}
// Fallback to cookies
if (!sealedSession)
sealedSession = getCookie(event, sessionName)
if (sealedSession) {
// Unseal session data from cookie
const unsealed = await unsealSession(
event,
config,
sealedSession,
).catch(() => {})
Object.assign(session, unsealed)
}
// New session store in response cookies
if (!session.id) {
session.id = (config.crypto || crypto).randomUUID()
session.createdAt = Date.now()
await updateSession(event, config)
}
return session
}