diff --git a/README.md b/README.md index 8fe3ae69..a6e99ffb 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ The following helpers are auto-imported in your `server/` directory. ```ts // Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call // Only store the data that allow you to recognize an user, but do not store sensitive data +// Merges new data with existing data using defu() await setUserSession(event, { user: { // ... user data @@ -98,6 +99,9 @@ await setUserSession(event, { // Any extra fields }) +// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data +await replaceUserSession(event, data) + // Get the current user session const session = await getUserSession(event) diff --git a/src/module.ts b/src/module.ts index 6366a3b3..1de8f817 100644 --- a/src/module.ts +++ b/src/module.ts @@ -42,6 +42,7 @@ export default defineNuxtModule({ 'sessionHooks', 'getUserSession', 'setUserSession', + 'replaceUserSession', 'clearUserSession', 'requireUserSession', ] diff --git a/src/runtime/server/utils/session.ts b/src/runtime/server/utils/session.ts index 2f5b1c9f..b16b7db5 100644 --- a/src/runtime/server/utils/session.ts +++ b/src/runtime/server/utils/session.ts @@ -36,6 +36,20 @@ export async function setUserSession (event: H3Event, data: UserSession) { return session.data } +/** + * Replace a user session + * @param event + * @param data User session data, please only store public information since it can be decoded with API calls + */ +export async function replaceUserSession (event: H3Event, data: UserSession) { + const session = await _useSession(event) + + await session.clear() + await session.update(data) + + return session.data +} + export async function clearUserSession (event: H3Event) { const session = await _useSession(event)