Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit 5f435a9

Browse files
authored
feat: rename to useSession, allow partial options via defu (#5)
* feat!: rename useNuxtSession to just useSession (thx, @atinux) * feat!: make some api options optional, actually rename composable file * chore: update changelog to point to releases page
1 parent d842c5d commit 5f435a9

File tree

7 files changed

+45
-48
lines changed

7 files changed

+45
-48
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Changelog
22

3+
See more recent releases on the releases page: https://github.com/sidebase/nuxt-session/releases
4+
35
## 0.1.2 (2022/10/13)
46

57
- fix: remove dependency on self

README.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@
99
[![Follow us on Twitter](https://badgen.net/badge/icon/twitter?icon=twitter&label)](https://twitter.com/sidebase_io)
1010
[![Join our Discord](https://badgen.net/badge/icon/discord?icon=discord&label)](https://discord.gg/9MUHR8WT9B)
1111

12-
> Nuxt session middleware to get a persistent session per app user, e.g., to store data across multiple requests. The nuxt session module provides the `useNuxtSession()` composable out of the box and sets up API endpoints to interact with your session to make working with sessions feel like a breeze.
12+
> Nuxt session middleware to get a persistent session per app user, e.g., to store data across multiple requests. The nuxt session module provides the `useSession()` composable out of the box and sets up API endpoints to interact with your session to make working with sessions feel like a breeze.
1313
1414
## Quick start
1515

1616
1. Install the package:
1717
```bash
18-
npm i @sidebase/nuxt-session
18+
npm i -D @sidebase/nuxt-session
1919
```
2020
2. Add the package to your `nuxt.config.ts`:
2121
```bash
@@ -26,7 +26,7 @@
2626
3. Done! Each client will now have a unique session you can access on the server- and client side:
2727
- client-side (from any `.vue` file):
2828
```ts
29-
const { session, refresh, update, reset } = await useNuxtSession()
29+
const { session, refresh, update, reset } = await useSession()
3030
3131
// Reactive session object that updates after methods calls below
3232
session.value
@@ -51,7 +51,7 @@ The `nuxt-session` library provide many helpers to interact with the session fro
5151
## Features
5252
5353
- ✔️ Persistent sessions across requests using cookies
54-
- ✔️ `useNuxtSession` composable for client side session-interaction
54+
- ✔️ `useSession` composable for client side session-interaction
5555
- ✔️ Configurable session endpoints out of the box:
5656
- `GET /api/session`: Get the current session
5757
- `DELETE /api/session`: Delete the current session
@@ -120,7 +120,7 @@ const {
120120
reset,
121121
update,
122122
overwrite
123-
} = await useNuxtSession()
123+
} = await useSession()
124124
125125
// The session itself, a ref that automatically updates when you use the other methods below
126126
session.value
@@ -145,7 +145,7 @@ Per default all of the above is enabled. Read on if you want to learn how to con
145145
146146
You can configure what endpoints and utilities `nuxt-session` adds for client-side use using the module configuration. The API is fully enabled per default. If you want to turn off the whole `nuxt-session` API you can set `session: { api: { isEnabled: false } }` in the module config in your `nuxt.config.ts`. If you want to keep the api enabled but allow just certain operation by the client-side, you can restrict the HTTP methods that should be allowed. E.g., `session: { api: { methods: ['get'] } }` would:
147147
- add only one endpoint that allows reading the current session data (per default: `GET /api/session`)
148-
- enable only the `session` and `refresh` properties of the `useNuxtSession` composable
148+
- enable only the `session` and `refresh` properties of the `useSession` composable
149149
150150
After this, calling the `reset()` or `update()` functions from above would result in an error that the methods are not supported and the api endpoints would not be added to your nuxt-app. This way:
151151
- you cannot accidentaly call a composable-method during development and it later does not work in production,

package-lock.json

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"dependencies": {
3232
"@nuxt/kit": "^3.0.0-rc.12",
3333
"dayjs": "^1.11.5",
34+
"defu": "^6.1.0",
3435
"h3": "^0.8.5",
3536
"unstorage": "^0.6.0"
3637
},

playground/app.vue

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<script setup lang="ts">
22
import { useFetch } from '#app'
33
import { computed, ref } from 'vue'
4-
import { useNuxtSession } from '#imports'
4+
import { useSession } from '#imports'
55
6-
const { session, refresh, reset, remove, update } = await useNuxtSession()
6+
const { session, refresh, reset, remove, update } = await useSession()
77
88
// Counter demo
99
const { refresh: increaseCountOnServer } = await useFetch('/api/count', { server: false, immediate: false })
@@ -33,7 +33,7 @@ const value = ref('')
3333
<hr>
3434
<div>
3535
<h3>Counting</h3>
36-
<p>With nuxt-session you can either access the current user session safely on the server side using `event.context.session`. You can also use the `update`-method of the `useNuxtSession` composable that allows arbitrary updating of session data from the client-side.</p>
36+
<p>With nuxt-session you can either access the current user session safely on the server side using `event.context.session`. You can also use the `update`-method of the `useSession` composable that allows arbitrary updating of session data from the client-side.</p>
3737
<p>Below both possible options are show-cased. One button triggers a request to the `/api/count` endpoint that increases the request count on the server side. The second button sends a JSON-payload to the nuxt-session API endpoint that allows arbitrary updating of session data with data sent from the client side.</p>
3838
<p>When you increase the count on the server-side, the session here will not change. You need to hit the `refresh` button above to see the changes! When we update it from the client-side using the nuxt-session composable `update` for it, we immeadiatly see the updates reflected, neat!</p>
3939
<p>NOTE: The server-side and client-side count update can collide with each other, e.g., if you update the count on the server side a couple of times and then update the count from the client side without refreshing the session. As the client only has the "old" count, it will send a different count than the count that the server currently knows and thus overwrite it.</p>

src/module.ts

Lines changed: 30 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { resolve } from 'path'
22
import { fileURLToPath } from 'url'
33
import { addImportsDir, addServerHandler, defineNuxtModule, useLogger } from '@nuxt/kit'
44
import { CreateStorageOptions } from 'unstorage'
5+
import { defu } from 'defu'
56

67
export type SameSiteOptions = 'lax' | 'strict' | 'none'
78
export type SupportedSessionApiMethods = 'patch' | 'delete' | 'get' | 'post'
@@ -84,16 +85,32 @@ export interface ModuleOptions {
8485
* Configure session-behvaior
8586
* @type SessionOptions
8687
*/
87-
session: SessionOptions
88+
session: Partial<SessionOptions>
8889
/**
8990
* Configure session-api and composable-behavior
9091
* @type ApiOptions
9192
*/
92-
api: ApiOptions
93+
api: Partial<ApiOptions>
9394
}
9495

9596
const PACKAGE_NAME = 'nuxt-session'
9697

98+
const defaults: ModuleOptions = {
99+
isEnabled: true,
100+
session: {
101+
expiryInSeconds: 60 * 10,
102+
idLength: 64,
103+
storePrefix: 'sessions',
104+
cookieSameSite: 'lax',
105+
storageOptions: {}
106+
},
107+
api: {
108+
isEnabled: true,
109+
methods: [],
110+
basePath: '/api/session'
111+
}
112+
}
113+
97114
export default defineNuxtModule<ModuleOptions>({
98115
meta: {
99116
name: `@sidebase/${PACKAGE_NAME}`,
@@ -102,48 +119,24 @@ export default defineNuxtModule<ModuleOptions>({
102119
bridge: false
103120
}
104121
},
105-
defaults: {
106-
isEnabled: true,
107-
session: {
108-
expiryInSeconds: 60 * 10,
109-
idLength: 64,
110-
storePrefix: 'sessions',
111-
cookieSameSite: 'lax',
112-
storageOptions: {}
113-
},
114-
api: {
115-
isEnabled: true,
116-
methods: [],
117-
basePath: '/api/session'
118-
}
119-
},
122+
defaults,
120123
hooks: {},
121-
setup (options, nuxt) {
124+
setup (moduleOptions, nuxt) {
122125
const logger = useLogger(PACKAGE_NAME)
123126

124127
// 1. Check if module should be enabled at all
125-
if (!options.isEnabled) {
128+
if (!moduleOptions.isEnabled) {
126129
logger.info(`Skipping ${PACKAGE_NAME} setup, as module is disabled`)
127130
return
128131
}
129132

130133
logger.info('Setting up sessions...')
131134

132135
// 2. Set public and private runtime configuration
133-
const moduleOptions = {
134-
...options,
135-
api: {
136-
...options.api,
137-
methods: options.api.methods.length > 0 ? options.api.methods : ['patch', 'delete', 'get', 'post']
138-
}
139-
}
140-
nuxt.options.runtimeConfig.session = moduleOptions
141-
nuxt.options.runtimeConfig.public = {
142-
...(nuxt.options.runtimeConfig.public || {}),
143-
session: {
144-
api: moduleOptions.api
145-
}
146-
}
136+
const options = defu(moduleOptions, defaults)
137+
options.api.methods = moduleOptions.api.methods.length > 0 ? moduleOptions.api.methods : ['patch', 'delete', 'get', 'post']
138+
nuxt.options.runtimeConfig.session = defu(nuxt.options.runtimeConfig.session, options)
139+
nuxt.options.runtimeConfig.public = defu(nuxt.options.runtimeConfig.public, { session: { api: options.api } })
147140

148141
// 3. Locate runtime directory and transpile module
149142
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
@@ -157,12 +150,12 @@ export default defineNuxtModule<ModuleOptions>({
157150
nuxt.options.serverHandlers.unshift(serverHandler)
158151

159152
// 5. Register desired session API endpoints
160-
if (moduleOptions.api.isEnabled) {
161-
for (const apiMethod of moduleOptions.api.methods) {
153+
if (options.api.isEnabled) {
154+
for (const apiMethod of options.api.methods) {
162155
const handler = resolve(runtimeDir, `server/api/session.${apiMethod}`)
163-
addServerHandler({ handler, route: moduleOptions.api.basePath })
156+
addServerHandler({ handler, route: options.api.basePath })
164157
}
165-
logger.info(`Session API "${moduleOptions.api.methods.join(', ')}" endpoints registered at "${moduleOptions.api.basePath}"`)
158+
logger.info(`Session API "${options.api.methods.join(', ')}" endpoints registered at "${options.api.basePath}"`)
166159
} else {
167160
logger.info('Session API disabled')
168161
}
File renamed without changes.

0 commit comments

Comments
 (0)