sidebase / nuxt-session

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.
https://sidebase.io/nuxt-session/
MIT License
188 stars 19 forks source link

Can I write to the session on the server? #62

Closed marr closed 1 year ago

marr commented 1 year ago

Ask your question

I am trying to use the session module inside a server plugin. I thought accessing the ssrContext.event.session might work, but it appears not to. Is something like this possible?

export default defineNuxtPlugin((nuxtApp) => {
  const { session } = nuxtApp.ssrContext?.event.context || {};
  if (session && session.user) {
    useState("user", () => session.user);
  }
});

Additional information

The docs say:

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!

Does that mean I can't write to the session inside nuxt middleware?

BracketJohn commented 1 year ago

The session is not defined within server-plugins: A session is always connected to an incoming request of a user. Inside a server plugin we do not have that request, so we do not have a session (:

You can basically use the session everywhere where you have access to an event: H3Event 🎊 This is the case in endpoints and in server-middleware.

Hope that helps - let me know if there's anything else (:

bissolli commented 1 year ago

You can basically use the session everywhere where you have access to an event: H3Event 🎊 This is the case in endpoints and in server-middleware.

@BracketJohn I am trying to access the event.context.session from my server-middleare but it comes empty. Am I missing anything?

Look at this example: image

This is a simple server/middleware followed by a server/api.