Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
@sidebase/nuxt-session
Advanced tools
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.
npm i @sidebase/nuxt-session
nuxt.config.ts
:
export default defineNuxtConfig({
modules: ['@sidebase/nuxt-session'],
})
.vue
file):
const { session, refresh, update, reset } = await useNuxtSession()
// Reactive session object that updates after methods calls below
session.value
// Refresh the session
await refresh()
// Update the session with arbitrary data
await update({ test: 123 })
// Get a new session, all data will be lost, the session id and creation time will change
await reset()
server/api
files):
// Return all session data to the frontend
export default defineEventHandler(event => event.context.session)
The nuxt-session
library provide many helpers to interact with the session from the client- and server-side For more documentation and examples look at the documentation
useNuxtSession
composable for client side session-interactionGET /api/session
: Get the current sessionDELETE /api/session
: Delete the current sessionPOST /api/session
: Overwrite the current session dataPATCH /api/session
: Add to the current session dataUse the module-playground (see playground below) to play around with the module. Read the documentation if you want to learn about the library without starting your local environment.
An example page making use of nuxt-session
:
See the playground to interactively use this:
> git clone https://github.com/sidebase/nuxt-session
> cd nuxt-session
> npm i
> npm run dev:prepare
> npm run dev
# -> open http://localhost:3000
First of all: Try out the playground if you want to test-drive this package and learn how to use it. You can also have a look at the playground code to see how to use nuxt-session
in your app.
The nuxt-session
maintains sessions: Persistent data across different requests by the same client (or: "user"). To maintain these sessions, nuxt-session
sets a cookie with a unique client id for the currently connected client. Then after the cookie is set, the client will be uniquely identifiable by the server as long as:
We call this "stay" that lasts as long as the above criteria are met a session.
Below we describe:
The session that nuxt-session
maintains for you also allows you to store arbitrary data in a storage across requests for the entire duration of the session. nuxt-session
makes this data available to you in different ways, depending on whether you are on the client side (e.g., .vue
components that are seen by your users) or on the server-side (e.g., inside an endpoint in the server/api/
directory).
Reading session data is generally safe on both the client- and server-side, unless it contains anything you don't want your users to see.
Allowing alteration of session-data with arbitrary data provided by the client (e.g., your user) should be treated carefully, but can be safely done if you don't care about your users polluting sessions, have authentication and authorization or are generally not concerned about the security of your app. If you want
On the client-side you can use the session like this:
const {
session,
refresh,
remove,
reset,
update,
overwrite
} = await useNuxtSession()
// The session itself, a ref that automatically updates when you use the other methods below
session.value
// Refresh the session, e.g., after you've changed the session on the server side OR when you don't have an active session at the moment
await refresh()
// Delete the current session without getting a new one. Note that the next request will automatically get a new session
await remove()
// Reset the session: Under the hood this calls `remove` and then `refresh`
await reset()
// Update the current session with arbitrary data, this data is merged into the current session with the spread-syntax, so existing data remains (unless you provide new data with the same key!)
await update({ "hello": "session", "test": 1234, "userLikesCookies": true })
// Overwrite
await overwrite({ "test": "This replaces all current data of the session without overwriting the current session itself" })
Per default all of the above is enabled. Read on if you want to learn how to configure and disable some of the above functionalities and their respective endpoints, e.g., to secure your application.
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:
GET /api/session
)session
and refresh
properties of the useNuxtSession
composableAfter 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:
For all configuration options check out the configuration section.
The methods that nuxt-session
expose are useFetch
calls under the hood. For advanced use, debugging and error handling their result is directly exposed. So when you use one of them, you can destructure just like with nuxt useFetch:
const { data, pending, error, refresh } = await update({ "hello": "session", "test": 1234, "userLikesCookies": true })
// ... do something with the above reactive useFetch properties
nuxt-session
makes the data of the current session available to all endpoints and middlewares as part of the event
that is passed into the endpoints and middlewares at event.context.session
. For example here's how you can implement a server-side request counting endpoint that stores how many requests to this endpoint where performed by that specific session:
// File: `playground/server/api/count.get.ts`
export default defineEventHandler((event) => {
// Get the current count or set to 0 if this is the first request
const currentCount = event.context.session.count || 0
// Increase the count (nuxt-session will persist all changes made to `event.context.session` after the return)
event.context.session.count = currentCount + 1
// Return the count
return event.context.session.count
})
All changes made to the event.context.session
are automatically stored for subsequent requests by nuxt-session
. So the count is set to 0
on the first request and then increases by 1
on every subsequent request.
The server-side session also contains it's own meta-data of the form:
declare interface Session {
id: string
createdAt: Date
}
In theory you can manipulate this data on the server side if you want to. If you do this, the session will likely become invalid in the process, so proceed at your own risk!
nuxt-session
allows you to use different storage backends. A storage backend is something like your server memory, a redis database, the file-system of your server, ... Supporting these backend is possible by using unjs/unstorage for storage management. This library connects to the different backends it supports with a unified interface.
You can configure the storage backend using the session.session.storageOptions
configuration option of the nuxt-session
module. By default memory
is used to store the sessions. This has some advantages like speed and easy setup, but some disadvantages like missing persistency (if your server crashes, the sessions are gone!) and possible exploits like setting millions of sessions trying to exhaust your server-memory or saving large amounts of data into the session that your server cannot handle.
Check out here what storage backends are supported and how to configure them: https://github.com/unjs/unstorage#drivers
Here's what the full default module configuration looks like:
{
// Module is enabled
isEnabled: true,
session: {
// Sessions expire after 600 seconds = 10 minutes
expiryInSeconds: 60 * 10,
// Session ids are 64 characters long
idLength: 64,
// All session data is stored in a "sub-storage" that uses the `sessions` prefix
storePrefix: 'sessions',
// The session cookie same site policy is `lax`
cookieSameSite: 'lax',
// In-memory storage is used (these are `unjs/unstorage` options)
storageOptions: {}
},
api: {
// The API is enabled
isEnabled: true,
// `PATCH, GET, POST, DELETE /api/session` HTTP requests are possible
methods: ['patch', 'get', 'post', 'delete'],
// The sessions endpoints are mounted at `/api/session`
basePath: '/api/session'
}
}
This section mostly contains a list of possible security problems and how to mitigate (some) of them. Note that the below flaws exist with many libraries and frameworks we use in our day-to-day when building and working with APIs. E.g., your vanilla-nuxt-app is not safe of some of them like the client sending malicious data. Missing in the below list are estimates of how likely it is that one of the list-items may occur and what impact it will have on your app. This is because that heavily depends on:
Without further ado, here's some attack cases you can consider and take action against. Neither the attack vectors, the problems or the mitigations are exhaustive:
api.isEnabled: false
) or restrict it to only reading (api: { methods: ['get'] }
)redis
as a storage backend and set data to expire automaticallyapi: { methods: [] }
64
characters it already is quite long, in 2022)session.cookieSameSite: 'stric'
(default: lax
)A last reminder: This library was not written by crypto- or security-experts. So please proceed at your own risk, inspect the code if you want to and open issues / pull requests where you see room for improvement. If you want to file a security-concern privately, please send an email to support@sidestream.tech
with the subject saying "SECURITY nuxt-session" and we'll look into your request ASAP.
npm run dev:prepare
to generate type stubs.npm run dev
to start the module playground in development mode.npm run lint
to run eslintnpm run type
to run typescheck via tscFAQs
**DEPRECATION NOTICE:** `nuxt-session` will be depreacated at the 11.12.2023 - read https://github.com/sidebase/nuxt-session/issues/91 for reasoning and process. We recommend migrating to [`h3` sessions](https://github.com/unjs/h3#session) for your applic
The npm package @sidebase/nuxt-session receives a total of 725 weekly downloads. As such, @sidebase/nuxt-session popularity was classified as not popular.
We found that @sidebase/nuxt-session demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.